Java Packages
Java Packages Interview with follow-up questions
1. What is a package in Java?
A package is a namespace that groups related classes, interfaces, enums, and records. It serves three purposes: organization (logical grouping of related types), name-conflict avoidance (two classes can share a simple name in different packages, e.g. java.util.Date vs java.sql.Date), and access control (members with no modifier are package-private, visible only within the same package).
package com.example.orders; // declares the package
import com.example.payments.PaymentService; // use a type from another package
Points interviewers like: the package name maps to a directory structure (com/example/orders/), the convention is reversed domain name (com.company.project) to keep it globally unique, and members are resolved by their fully-qualified name (com.example.orders.Order). The java.* and javax.*/jakarta.* packages form the standard library.
A current note: since Java 9, packages are themselves grouped into modules (the Java Platform Module System), which add a stronger layer of encapsulation on top of packages — a module's module-info.java controls which packages it exports. So packages organize types; modules organize and encapsulate packages. Mentioning that relationship shows up-to-date knowledge.
Follow-up 1
What are the advantages of using packages in Java?
There are several advantages of using packages in Java:
Organization and Management: Packages help in organizing and managing large-scale Java applications. They provide a way to group related classes and interfaces together, making it easier to locate and maintain code.
Namespace Management: Packages provide a namespace to avoid naming conflicts. By using packages, you can have classes with the same name in different packages without any conflict.
Access Control: Packages allow access control through the use of access modifiers. Classes and interfaces within a package can be declared as public, protected, or package-private, controlling their visibility and accessibility from other packages.
Code Reusability: Packages promote code reusability. By organizing related classes and interfaces in a package, they can be easily reused in other projects or modules.
Encapsulation: Packages provide a level of encapsulation. Classes and interfaces within a package can be declared as public, protected, or package-private, controlling their visibility and accessibility from other packages.
Follow-up 2
Can you explain the concept of package hierarchy in Java?
In Java, packages can be organized in a hierarchical structure known as the package hierarchy. The package hierarchy is a way to organize packages in a tree-like structure, where each package is a node in the tree.
For example, consider the following package hierarchy:
com
└── example
├── utils
│ ├── FileUtil.java
│ └── StringUtil.java
├── models
│ ├── User.java
│ └── Product.java
└── Main.java
In this example, the com.example package is the root package, and it contains two sub-packages: utils and models. Each sub-package can further contain sub-packages or classes.
The package hierarchy helps in organizing related packages and provides a way to navigate and access classes and interfaces within the packages.
Follow-up 3
How can we access a package from another package?
In Java, to access a package from another package, you need to use the import statement. The import statement is used to make classes and interfaces from one package available to another package.
To access a package from another package, follow these steps:
- Use the
importstatement at the beginning of your Java file. - Specify the fully qualified name of the class or interface you want to import.
For example, if you have a class com.example.utils.FileUtil in the com.example.utils package and you want to use it in another package, you can import it as follows:
import com.example.utils.FileUtil;
After importing the class, you can use it in your code without specifying the fully qualified name.
Note: If the class or interface you want to import is in the same package or a sub-package of the current package, you don't need to use the import statement.
Follow-up 4
What is the difference between import and static import in Java?
In Java, both import and static import are used to make classes and interfaces available in other classes. However, there is a difference between them:
Import: The
importstatement is used to import classes and interfaces from a package. It allows you to use the imported classes and interfaces without specifying their fully qualified names.Static Import: The
static importstatement is used to import static members (fields and methods) from a class. It allows you to use the imported static members directly without qualifying them with the class name.
Here's an example to illustrate the difference:
import java.util.ArrayList;
import static java.lang.Math.PI;
public class Main {
public static void main(String[] args) {
ArrayList list = new ArrayList<>();
list.add("Hello");
list.add("World");
double radius = 5.0;
double area = PI * radius * radius;
System.out.println(list);
System.out.println(area);
}
}
In this example, the import java.util.ArrayList statement allows you to use the ArrayList class without specifying its fully qualified name. The static import java.lang.Math.PI statement allows you to use the PI constant directly without qualifying it with the Math class name.
2. What is the difference between a package and a module in Java?
They're different levels of organization, and a module contains packages:
- Package — a namespace grouping related classes/interfaces; provides name-spacing and package-private access. It does not control which other code can use its public types — anything on the classpath can access a package's
publicmembers. - Module (Java 9+, the Java Platform Module System / "Project Jigsaw") — a higher-level unit grouping one or more packages, declared in a
module-info.java. It adds strong encapsulation and explicit dependencies: a module only exposes packages it explicitlyexports, and only sees other modules it explicitlyrequires.
// module-info.java
module com.example.orders {
requires com.example.payments; // explicit dependency
exports com.example.orders.api; // only this package is visible outside
}
The distinction interviewers want: a package is logical grouping + namespacing; a module is encapsulation + dependency management at the JAR/component level. Modules let you hide internal packages (true encapsulation the classpath never offered) and enable tooling like jlink to build minimal custom runtimes.
An honest current note: the JDK itself is fully modularized, but many applications still run on the classpath rather than adopting JPMS, so modules are widely used (the JDK) but less universally authored by app developers — worth acknowledging.
Follow-up 1
Can you explain the concept of modules in Java 9?
In Java 9, modules are a new way to organize and package code. A module is a self-contained unit of code that encapsulates its implementation details and exposes a set of public APIs. It consists of a module declaration file called module-info.java and one or more packages.
The module declaration file, module-info.java, specifies the module's name, dependencies on other modules, and the packages it exports. It also defines the module's public API, which is accessible to other modules.
Modules provide a higher level of encapsulation compared to packages. They allow for better modularization of large codebases, making it easier to manage dependencies and enforce encapsulation boundaries. Modules also improve the maintainability and security of Java applications by enforcing explicit dependencies and preventing unwanted access to internal implementation details.
Follow-up 2
How does the module system improve the security and maintainability of Java applications?
The module system in Java improves the security and maintainability of applications in several ways:
Encapsulation: Modules provide a higher level of encapsulation compared to packages. They encapsulate their implementation details and expose a set of public APIs. This allows for better separation of concerns and reduces the risk of unwanted access to internal implementation details.
Explicit Dependencies: Modules enforce explicit dependencies between modules. This means that modules must explicitly declare their dependencies on other modules. This improves the maintainability of applications by making it clear which modules depend on each other and preventing accidental dependencies.
Strong Encapsulation: Modules can specify which packages are accessible to other modules. This allows for fine-grained control over the visibility of code and prevents unwanted access to internal implementation details.
Improved Security: The module system provides a mechanism for controlling access to internal APIs. Modules can specify which packages are accessible to other modules, preventing unwanted access to sensitive code.
Overall, the module system improves the security and maintainability of Java applications by providing better encapsulation, explicit dependencies, and control over code visibility.
Follow-up 3
What is the role of the module-info.java file in a module?
The module-info.java file is a module declaration file that plays a crucial role in defining a module in Java. It is located in the root directory of a module and has the name module-info.java.
The module-info.java file contains the following information:
Module Name: It specifies the name of the module.
Module Dependencies: It specifies the dependencies of the module on other modules.
Exported Packages: It specifies the packages that are accessible to other modules.
Required Services: It specifies the services required by the module.
Provided Services: It specifies the services provided by the module.
The module-info.java file is compiled along with the module's source code and is used by the Java module system to enforce module boundaries, resolve dependencies, and control access to code. It provides a way to define the module's public API and encapsulate its implementation details.
3. How do you create a package in Java?
You create a package by putting a package declaration at the top of your source file (it must be the first non-comment line), and placing the file in a matching directory:
// File: src/com/example/orders/Order.java
package com.example.orders;
public class Order { ... }
The directory structure mirrors the package name: com/example/orders/Order.java. Compiling with javac -d out src/com/example/orders/Order.java puts the class in out/com/example/orders/Order.class, and you reference it elsewhere as com.example.orders.Order (or via import).
Practical points interviewers expect: use the reversed-domain convention (com.company.product) for uniqueness; one public top-level class per file, named to match; and a file may declare only one package.
The current reality worth noting: you almost never manage this by hand. Build tools — Maven or Gradle — and the IDE enforce the standard layout (src/main/java/com/example/...), handle compilation and the classpath/module-path, and package everything into a JAR. So the concept (package declaration + matching directory) is what's tested, but in practice the build tool does the wiring.
Follow-up 1
What is the naming convention for packages in Java?
The naming convention for packages in Java is to use lowercase letters for the package name. It is recommended to use a reverse domain name as the package name to ensure uniqueness. For example, if your domain name is 'example.com', you can use 'com.example' as the package name. Additionally, it is common to use meaningful names for the package that reflect the purpose or functionality of the classes it contains.
Follow-up 2
Can we have two classes with the same name in a package?
No, we cannot have two classes with the same name in a package. Each class within a package must have a unique name. However, it is possible to have multiple packages with classes that have the same name, as long as they are in different packages.
Follow-up 3
How can we compile a Java file that is part of a package?
To compile a Java file that is part of a package, you need to navigate to the directory that contains the package directory. For example, if your package is named 'com.example' and the Java file you want to compile is 'MyClass.java', you need to navigate to the directory that contains the 'com' directory.
Once you are in the correct directory, you can use the 'javac' command followed by the path to the Java file. For example, to compile 'MyClass.java', you can use the following command:
javac com/example/MyClass.java
This will compile the Java file and generate the corresponding bytecode file (.class) in the same directory.
4. What is the purpose of the 'import' keyword in Java?
import lets you refer to types from other packages by their simple name instead of their fully-qualified name — it's a compile-time convenience for readability, not a runtime "include" (no code is copied; the compiler just resolves names).
import java.util.ArrayList; // single-type import
import java.util.*; // on-demand (wildcard) import
import static java.lang.Math.PI; // static import of a member
var list = new ArrayList(); // no need for java.util.ArrayList
Points interviewers like:
java.lang(String, Object, Math, etc.) is imported automatically — no import needed.- Wildcard
*imports a whole package on demand (it does not recurse into subpackages and has no runtime cost), but explicit imports are generally preferred for clarity. import staticbrings in static members (PI,assertEquals) so you can use them unqualified — handy in tests, but overuse hurts readability.- You don't import classes from the same package, and to use two same-named classes from different packages you fully-qualify one.
So import is purely about name resolution at compile time — it doesn't affect what's loaded at runtime (the class loader does that). IDEs/build tools manage imports automatically.
Follow-up 1
What is the difference between import and package statements in Java?
The 'import' statement is used to import specific classes or packages into a Java source file, while the 'package' statement is used to declare the package that the current source file belongs to. The 'import' statement allows you to use classes and packages from other files or libraries, while the 'package' statement helps in organizing and categorizing related classes into packages.
Follow-up 2
What happens if we do not use the import statement in Java?
If you do not use the import statement in Java, you will have to fully qualify the names of the classes and packages you want to use. For example, instead of using 'ArrayList' directly, you would have to use 'java.util.ArrayList' every time you want to use the ArrayList class. This can make the code more verbose and harder to read.
Follow-up 3
Can we import the same package or class multiple times in a Java program?
No, you cannot import the same package or class multiple times in a Java program. Once a package or class is imported, it is available for use throughout the entire source file. Importing it again will result in a compilation error. However, you can import multiple classes from the same package using a single import statement by separating the class names with commas.
5. What is a subpackage in Java?
A subpackage is simply a package nested inside another package — e.g. com.example.orders.api is a subpackage of com.example.orders. It maps to a nested directory (com/example/orders/api/) and is used to organize a large codebase into a finer hierarchy (e.g. ...orders.api, ...orders.internal, ...orders.model).
package com.example.orders.api; // a subpackage of com.example.orders
The crucial gotcha interviewers test: in Java, the subpackage relationship is purely organizational/naming — there is NO special access relationship. A subpackage is a completely separate package for visibility purposes: classes in com.example.orders cannot access package-private members of com.example.orders.api (and vice versa), and a wildcard import like import com.example.orders.* imports types in that package only, not its subpackages. So nesting doesn't grant any inherited access.
A current note: because packages give no cross-package encapsulation between a package and its subpackages, the module system (JPMS) is what lets you mark some subpackages as internal (not exported) so they're hidden from other modules — the modern way to truly hide "internal" subpackages. The naming hierarchy is for humans/organization; access is controlled by modifiers and modules, not by the package nesting itself.
Follow-up 1
How can we create a subpackage in Java?
To create a subpackage in Java, you simply need to include the desired subpackage name as part of the package declaration in the source file. For example, if you want to create a subpackage named 'subpackage' within a package named 'package', the package declaration in the source file would be:
package package.subpackage;
Follow-up 2
Can a subpackage access the members of its superclass?
Yes, a subpackage can access the members of its superclass as long as the members are declared with the appropriate access modifiers (e.g., public, protected). If a member is declared as private, it cannot be accessed by the subpackage.
Follow-up 3
What is the difference between a package and a subpackage in Java?
The main difference between a package and a subpackage in Java is their hierarchical relationship. A package is the top-level container for organizing classes and interfaces, while a subpackage is a package that is contained within another package. Subpackages provide a way to further organize and categorize classes and interfaces within a package.
Live mock interview
Mock interview: Java Packages
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.