Interview Q&A · Java · 4 questions in this topic
Imports, Classpath and JARs — Java Interview Q&A
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
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
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
jar --create --file app.jar --main-class com.example.Main -C out . java -jar app.jar // runs without unpacking
What are static imports?
Answer
Static imports, available since Java 5, let you use static members without qualifying them with the class name. You can import a single member or all static members with an asterisk. They suit widely used constants and helpers but should be used sparingly because overuse makes the origin of a name unclear and risks ambiguity.
Example
import static java.lang.Math.PI; import static java.lang.Math.*; double area = PI * r * r; // no Math prefix needed
💡 Limit static imports to famous constants and assertion helpers to keep code readable.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission