Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Karrtik Iyer
Karrtik Iyer
3,738 Points

Java : Difference between folder and package

I am undergoing java web development tract and I often get confused when I hear that frameworks sometimes need our code to be in particular directory structure. And sometimes may be in particular package structure. Coming from a C++ background. I am trying to understand the difference between the folder structure and package structure in java (especially in web frameworks). And when to use what and why?

2 Answers

Craig Dennis
Craig Dennis
Treehouse Teacher

Java has different class loaders to find the appropriate class. The default class loader (and most) use a folder structure as means to finding the class. You can also package up these into a Jar (Java Archive) file which is basically just a glorified zip file, and the files inside are just zipped in folders.

The main reason for creating packages is to help avoid namespace collisions, two classes with the same name, and to help logically group and allow users of your code to find things better. Since the folder structure is solving a similar problem it was borrowed by the Java language.

I discuss this a bit in the Java Data Structures - Packages course. You might also want to dive a bit deeper using the Oracle Java SE tutorial on packages.

Hope it helps!

Bruno Areias
Bruno Areias
4,777 Points

A quote from the java's documentation:

"A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types."

In the end, a package (in the java's POV) is a collection of classes and subpackages, that eventually will be the core structure of an application or library.

In the other way, a JAVA package (in the IDE POV) is a normal folder that contains all it's .class or .java files.

Hope it was helpfull