Packages in Java — Java Technical Interview Questions & Answers

Packages in Java

Packages in Java

  • Packages are folders / namespaces that organise related classes. First line of the file: package com.shop.order; The folder path must match that statement.
  • import com.shop.order.Order; brings a class from another package. Packages avoid name clashes (two Order classes in different packages) and keep large projects tidy. Default access members are visible inside the same package.
  • Wrong folder vs wrong package statement is a compile headache. Interview line: package = namespace + organisation; import brings classes in.
  • Let's take this on the board with one tiny Main class — no extra files. Packages in Java — secret is private; outside code uses a getter. Start from main, go line by line, and stop at each print. That output is the proof for Packages.

Technical Interview Tip: package statement + matching folder structure.

Code Examples for Packages in Java

Example

// Same-file demo of access idea
class Box {
  private int secret = 7;
  int getSecret() { return secret; } // package/public API
}
public class Main {
  public static void main(String[] args) {
    System.out.println(new Box().getSecret());
  }
}

Packages in Java — secret is private; outside code uses a getter.

How to Explain Packages in Java to an Interviewer

What is a package?

Namespace / folder for related classes

Where does the package line go?

Top of the file

What does import do?

Brings a class from another package