Home > Interview Questions > Java Packages Explained

Java Packages Explained

So what is a Java package and what are the benefits? Great question that you will probably be asked during an interview for a Java position. A package is how a programmer or software developer can organize project files when the project contains multiple modules. A Java package will resolve naming conflicts when different projects have classes with the same name.

Package Benefits

  • Prevent Naming Conflicts
  • Provides Access Control
  • Bundle Like Classes and Interfaces
  • Re-usability of Code (classes and interfaces)

All related classes and interfaces are put into the same package. Once all of the classes and interfaces are in a package, we can simply import a needed class into our existing program or application. You can think of a package kind of like a directory structure.

Create a Package

The syntax to create a package is simple: package package-name;

package com.jcd.java.tutorials;

Import Class From Package

The syntax to import a package is just as simple: import package-name.class-name

import com.jcd.java.tutorials.JavaCodeDepotClass;

Prevent Naming Conflicts

Outside of organizing, the main benefit of a Java package is avoiding naming conflicts. Let’s look at the two package/import sets below. We can have a package named com.jcd.java.tutorialsOld and another package named com.jcd.java.tutorialsNew and they can both have the same Class called JavaCodeDepotClass. This is only possible with Java Packages.

package com.jcd.java.tutorialsOld;
import com.jcd.java.tutorialsOld.JavaCodeDepotClass;

package com.jcd.java.tutorialsNew;
import com.jcd.java.tutorialsNew.JavaCodeDepotClass;

Posted by


Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot