Java Basics
Java Basics
This domain checks whether you can read, compile, and run a small Java program and reason about declarations and scope. Expect questions on the JDK/JRE/JVM relationship, the main method, packages and imports, comments, and where variables live.
Toolchain and source structure
javaccompiles.javasource into.classbytecode;javastarts the JVM and runs a class.- JDK = development tools + JRE; JRE = JVM + core libraries. The JVM itself is platform-dependent, while bytecode is portable.
- A
publictop-level class must match its file name. Package declaration comes first, then imports, then type declarations. import java.util.*;imports types in that package only, not subpackages.
Entry point and scope
A runnable class needs public static void main(String[] args). Modifier order may vary and String... args is legal, but the method must be static, public, void, and named main.
Local variables are block-scoped and have no default value; instance and static fields do. Static members belong to the class, instance members to an object.
Worked example
public class Scope {
static int count;
public static void main(String[] args) {
int x = 1;
if (x > 0) {
int y = 2;
x = y;
}
System.out.println(y);
}
}
y is declared inside the if block, so the final line does not compile. count would print 0 because static fields receive default values.
Traps
- A local variable used before assignment is a compile error, not a runtime error.
System.gc()only suggests collection; it does not guarantee it.- Comments do not affect scope, but a comment cannot rescue a misplaced declaration.
- A non-public class may have a different file name, but only the public class can be launched by that name.