Java Basics
Java Fundamentals
Complete lesson for Java Fundamentals using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Java Fundamentals
Section: Java Basics. Program structure, tokens, keywords, javac/java execution steps, and the parts of the JVM.
Typical .java layout
- A
.javafile is read top to bottom: optional documentation comments → optionalpackage→importstatements →class(orinterface/enum/record) → fields → constructors → methods. - If this class is the program entry point, it contains
public static void main(String[] args). java.langis imported automatically (String,System,Object,Math) — you do not writeimport java.lang.String.- One public top-level type per file, and the file name must match that public type:
AddNumbers.java↔public class AddNumbers.
package demo;
public class FundamentalsDemo {
public static void main(String[] args) {
int count = 10;
System.out.println("count = " + count);
}
} Java program structure
A well-written .java file follows a stable top-to-bottom order:
documentation comments, optional package, import lines,
the class declaration, fields, constructors, methods, and
main when this class is the entry point. The diagram below labels each part
on a tiny AddNumbers example.
main - package / import: optional package first, then imports;
java.langis already there. - class: one public type; file name matches the public class name.
- members: fields, constructors, then methods.
- main: only the launcher class needs
public static void main(String[] args).
Tokens
- The compiler’s first job after reading characters is tokenisation: it groups source into keywords, identifiers, literals, operators, and separators (
;,,,.,(),{},[]). - Literals include integers (
42), longs (42L), doubles (3.14), floats (3.14f), chars ('A'), strings ("hi"), booleans, andnull. - Java is free-form whitespace; extra spaces and newlines do not change meaning. Statements end with
;(except class/method/block declarations). - Comments are not tokens that execute —
javacstrips//and/* */before parsing.
Keywords and identifiers
- Identifiers start with a letter,
$, or_, then letters, digits,$, or_. They cannot be keywords. - Convention:
PascalCasetypes,camelCasemethods/fields,UPPER_SNAKEconstants,lowercase.dot.separatedpackages. - Java 17 words you will meet early:
class,public,static,void,int,if,else,for,while,new,return,this,super,extends,implements,try,catch,finally,throw,throws,import,package. true,false, andnullare reserved literals — you still cannot use them as names.
| Token kind | Examples | Notes |
|---|---|---|
| Keyword | class, static, new | Reserved; cannot be identifiers |
| Identifier | score, HelloWorld | Names you choose |
| Literal | 17, "Java", true | Fixed values in source |
| Operator | +, &&, ?: | Act on operands |
| Separator | ; { } ( ) , . | Structure the program |
Compilation: javac and java
- Java does not produce a native
.exethe way C/C++ linkers do.javacwrites portable bytecode. javac Hello.javareads source, type-checks it, and writesHello.class.java Hellostarts a JVM, the class loader findsHello.class, the verifier checks the bytecode, thenmainruns.- Compile-time errors (missing
;, type mismatch) never reach the JVM. Runtime errors (NullPointerException,/ by zero) happen after launch. - On Java 11+ you may run a single file with
java Hello.java— the launcher still compiles to bytecode, just in memory.
Java program execution steps
Unlike C/C++, a simple Java program is not linked into a native .exe.
You write .java source, javac emits .class bytecode,
and the java launcher starts a JVM that loads, verifies, and runs it.
javac, bytecode, JVM, output
- Write / save: public class name = file name (
Hello.java). - javac: syntax + types →
Hello.class(not machine code). - java Hello: JVM + class loader + verifier + interpreter/JIT.
- Output:
System.out.printlnreaches the console.
Advanced — Java Fundamentals
Comments, Unicode, and source rules
//line comments,/* */block comments, and/** */Javadoc. Nested/* */is not allowed.- A file may contain extra package-private types, but at most one public top-level type; that type’s name is the file name.
var(Java 10+) is a reserved type name for local-variable type inference, not a classic keyword in every context.- Underscores in numeric literals (
1_000_000) are allowed since Java 7; a lone_is no longer a valid identifier (Java 9+). - Source files are Unicode. You can write
\uescapes, but interviews expect plain ASCII identifiers.
JVM architecture
- The JVM is a process that loads bytecode and runs it. Interview diagrams split it into three big parts: class loader subsystem, runtime data areas, and execution engine.
- Class loaders: bootstrap (core
java.*), platform/extension, and application (your classpath / module path). Delegation is parent-first. - Runtime data areas: method area (class metadata), heap (objects + arrays, GC lives here), per-thread Java stacks and PC registers, plus native method stacks.
- Execution engine: interpreter starts methods quickly; HotSpot JIT compiles hot methods to native code; GC reclaims unreachable heap objects.
- JNI lets bytecode call native C libraries. That is why a pure-Java program is portable, but a program with
.dll/.sofiles is not.
| JVM part | Stores / does | Interview one-liner |
|---|---|---|
| Class loader | Finds and loads .class files | Bootstrap → platform → application |
| Method area | Class structure, statics, bytecode | Per-JVM, shared by threads |
| Heap | Objects and arrays | Garbage collected |
| Java stack | Frames: locals + operand stack | One stack per thread |
| PC register | Current bytecode instruction | One per thread |
| Execution engine | Interpreter + JIT + GC | Turns bytecode into work |
JVM architecture
The JVM is the process that turns bytecode into running work. Interview sketches split it into a class loader subsystem, runtime data areas (heap, stacks, method area, PC registers), and an execution engine (interpreter, JIT, GC). JNI is the side door to native libraries.
- Class loaders: bootstrap → platform → application (parent-first).
- Heap: objects and arrays; garbage collected.
- Stack: per-thread frames (locals + operand stack).
- Engine: interpret first, JIT hot methods, GC unused objects.
Classpath, packages, and compile vs run errors
- Default classpath for a simple
javalaunch is the current directory (.). Packaged code must live in matching folders:package demo;→demo/FundamentalsDemo.class. - Then compile from the source root:
javac demo/FundamentalsDemo.javaand runjava demo.FundamentalsDemo. - “Cannot find symbol” is usually a missing import, wrong classpath, or a typo — a compile error.
- “Could not find or load main class” is a launch error: wrong name, wrong directory, or
.classnot on the classpath.
Tricky Interview Points
Q1) What are tokens in Java?
Answer The smallest elements the compiler recognizes: keywords, identifiers, literals, operators, and separators.
Q2) Can you use a keyword as a variable name?
Answer No. Keywords are reserved. int class = 1; does not compile.
Q3) What is the difference between javac and java?
Answer javac compiles .java source to .class bytecode. java launches the JVM, loads that class, and runs main.
Q4) Does javac create an .exe like a C compiler?
Answer No. javac writes bytecode (.class). The JVM interprets or JIT-compiles it. There is no separate linker step for a simple program.
Q5) Which package is imported by default?
Answer java.lang — that is why String and System need no import.
Q6) What is a legal identifier?
Answer It starts with a letter, $ or _, then letters, digits, $ or _. It must not be a keyword. Names like 1name or class are illegal.
Q7) Is main required in every class?
Answer No. Only the entry-point class needs main. Libraries and helper types have no main.
Q8) What is the usual order of sections in a .java file?
Answer Comments, optional package, imports, type declaration, fields, constructors, methods. The public class name must match the file name.
Q9) Name the three big parts of JVM architecture.
Answer Class loader subsystem, runtime data areas (heap, stacks, method area, PC), and execution engine (interpreter, JIT, GC).
Q10) What is stored on the heap vs the Java stack?
Answer Heap: objects and arrays (shared, garbage collected). Stack: per-thread frames with local variables and the operand stack. Primitive locals live in frames; object locals are references into the heap.
Q11) What does the bytecode verifier do?
Answer Before execution it checks that the .class file is well-formed and type-safe (no illegal jumps, stack underflow, or forged types). Failed verification is a link-time error.
Q12) What are the three class loaders beginners should name?
Answer Bootstrap (core JDK classes), platform/extension, and application (classpath). They use parent-first delegation.
Q13) Compile-time error vs runtime exception — give one example of each.
Answer Compile-time: missing semicolon or using a keyword as a name. Runtime: NullPointerException or dividing an int by zero after the program has started.
Q14) Why can two machines run the same Hello.class file?
Answer Bytecode is platform independent. Each OS ships a JVM that loads, verifies, and executes that bytecode. You do not rebuild an .exe per OS for pure Java.
Simple Programs
Tokens and a simple class structure
public class TokensDemo {
static final int MAX = 3; // constant identifier
public static void main(String[] args) {
int score = 10; // identifier + literal
score += MAX; // operator
System.out.println("score = " + score);
}
} Documented program with package-style comments
/**
* FundamentalsDemo — prints a welcome line.
* Compile: javac FundamentalsDemo.java
* Run: java FundamentalsDemo
*/
public class FundamentalsDemo {
public static void main(String[] args) {
System.out.println("Java fundamentals");
System.out.println("Tokens → javac → JVM → output");
}
} Helper class without main + runner with main
class Greeter {
static String hello(String name) {
return "Hello, " + name;
}
}
public class GreeterApp {
public static void main(String[] args) {
System.out.println(Greeter.hello("Java"));
}
} Show compile vs runtime (arithmetic)
public class ErrorKinds {
public static void main(String[] args) {
int a = 10;
int b = 2;
System.out.println("compile-ok sum = " + (a + b));
// Uncomment the next line after compiling once:
// int boom = a / 0; // runtime ArithmeticException
}
} Problem Solving Tricks
- If
javacis not found, the JDKbinfolder is not on PATH — you installed a runtime-only image or the wrong JDK. - Keep one public class per file until you know why you would do otherwise.
- Use
//comments while learning; add Javadoc when you write APIs. - Compile with matching versions:
javac --release 17 File.java. - Remember the pipeline as eight beats: write → save
.java→javac→.class→java→ class loader → verifier/JIT → output. - Heap holds objects; the stack holds frames. Drawing that picture answers half of “JVM architecture” questions.
- Package
demomeans folderdemo. Running from the wrong directory is the usual “cannot find main class” cause. java.langis always there — if youimport java.lang.Systeman interviewer may ask why it is unnecessary.
Practice Programs List
- List five token kinds and give one example of each from a 5-line program.
- Try naming a variable
staticand record the compiler message. - Write a class with a constant, a local variable, and a print statement, then compile it.
- Draw the steps: source → javac → bytecode → class loader → verifier → JVM → output.
- Label a JVM sketch: class loaders, heap, stack, method area, JIT, GC.
- Create two classes in two files where only one has
mainand call a method of the other. - Put the public class in package
demo, compile from the package root, and runjava demo.YourClass. - Add a Javadoc comment above
mainand generate docs withjavadocif the JDK tool is on PATH. - Break a program once with a missing
;(compile error) and once with/ 0(runtime) and compare the messages. - Print
System.getProperty("java.class.path")and explain what the class loader will search.