Interview Q&A · Java · 6 questions in this topic

Packages: Rules and Structure — Java Interview Q&A

All Java topics

How packages organize types, prevent name clashes, and control what source files may declare. Part of OOP Mechanics · 294 questions in the Java bank.

What are packages in Java?

Answer

A package groups related classes, interfaces, enums, and records into one named module and defines a namespace for them. That grouping resolves naming conflicts, because types such as com.shop.Order and com.blog.Order can coexist with full names. It also supports visibility control through package-private access, and by convention package names are lowercase reverse-domain names.

Key points

  1. 1Groups related types into one module for organization.
  2. 2Prevents name clashes through qualified namespaces.
  3. 3Enables package-private visibility for controlled sharing.

Can a source file have more than one package statement?

Answer

No, a compilation unit can have at most one package statement. Declaring two package statements in the same source file is a compile-time error because every top-level type in the file must belong to exactly one package.

Can the package statement come after import?

Answer

No, the package declaration must be the first non-comment statement in the file. The required order is an optional package statement, then import statements, then type declarations, so placing an import before the package causes a compile-time error.

Example

Example.javajava
package com.example.shop;
import java.util.List;
public class Order {}

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits