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

Imports, Classpath and JARs — Java Interview Q&A

All Java topics

How imports resolve names, where the JVM finds classes, and how JARs package them. Part of Objects, References & Memory · 294 questions in the Java bank.

What is the import keyword for?

Answer

The import statement lets you refer to a type by its short name instead of its fully qualified name. Single-type imports bring in one class while on-demand imports with an asterisk bring in a package for name resolution. Imports are compile-time only and add no runtime cost, java.lang is imported automatically, and static nested types are reached through their outer type.

Example

Example.javajava
import java.util.List;
import java.util.*; // on-demand: any public type in java.util
List<String> names = new ArrayList<>();

What is the classpath?

Answer

The classpath tells the compiler and JVM where to find compiled classes and resources. It is supplied through the CLASSPATH environment variable or the -cp and -classpath flags, and it can list directories and JAR files. Only parent directories are listed because the compiler maps package names to subdirectories beneath them.

Example

Example.javajava
javac -cp lib/app.jar:. Main.java
java -cp lib/app.jar:. Main

What is a JAR?

Answer

A JAR (Java Archive) is a ZIP file holding compiled classes, resources, and a manifest. An executable JAR names its entry point with a Main-Class manifest attribute so it can run without unpacking. The JVM reads classes directly from the archive, and since Java 9 modular JARs and the module system (JPMS) provide a stronger packaging successor.

Example

Example.javajava
jar --create --file app.jar --main-class com.example.Main -C out .
java -jar app.jar // runs without unpacking

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