Skip to main content

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.

L1

Basics — Java Fundamentals

Section: Java Basics. Program structure, tokens, keywords, javac/java execution steps, and the parts of the JVM.

Typical .java layout

  • A .java file is read top to bottom: optional documentation comments → optional package → import statements → class (or interface / enum / record) → fields → constructors → methods.
  • If this class is the program entry point, it contains public static void main(String[] args).
  • java.lang is imported automatically (String, System, Object, Math) — you do not write import 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.

Java program structure diagram with numbered parts: documentation comments, package statement, import section, class declaration, fields, constructor, methods, and public static void main as the entry point, around a sample AddNumbers.java editor window.
Java program structure — package, imports, class members, and main
  • package / import: optional package first, then imports; java.lang is 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, and null.
  • 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 — javac strips // and /* */ before parsing.

Keywords and identifiers

  • Identifiers start with a letter, $, or _, then letters, digits, $, or _. They cannot be keywords.
  • Convention: PascalCase types, camelCase methods/fields, UPPER_SNAKE constants, lowercase.dot.separated packages.
  • 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, and null are reserved literals — you still cannot use them as names.
Token kindExamplesNotes
Keywordclass, static, newReserved; cannot be identifiers
Identifierscore, HelloWorldNames you choose
Literal17, "Java", trueFixed values in source
Operator+, &&, ?:Act on operands
Separator; { } ( ) , .Structure the program

Compilation: javac and java

  • Java does not produce a native .exe the way C/C++ linkers do. javac writes portable bytecode.
  • javac Hello.java reads source, type-checks it, and writes Hello.class.
  • java Hello starts a JVM, the class loader finds Hello.class, the verifier checks the bytecode, then main runs.
  • 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.

Java program execution steps: write source in an editor, save Hello.java, compile with javac, produce Hello.class bytecode, run java Hello to start the JVM, class loader loads bytecode, verifier and JIT execute, then Hello Java prints on the console.
Java execution steps — write, 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.println reaches the console.
L2

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 \u escapes, 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 / .so files is not.
JVM partStores / doesInterview one-liner
Class loaderFinds and loads .class filesBootstrap → platform → application
Method areaClass structure, statics, bytecodePer-JVM, shared by threads
HeapObjects and arraysGarbage collected
Java stackFrames: locals + operand stackOne stack per thread
PC registerCurrent bytecode instructionOne per thread
Execution engineInterpreter + JIT + GCTurns 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.

JVM architecture diagram showing class loader subsystem with bootstrap, platform, and application loaders; runtime data areas with method area, heap, Java stacks, PC registers, and native method stacks; execution engine with interpreter, JIT compiler, and garbage collector; plus JNI and native libraries.
JVM architecture — class loaders, runtime memory, and the execution engine
  • 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 java launch 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.java and run java 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 .class not on the classpath.
L3

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.

L4

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
    }
}
L5

Problem Solving Tricks

  • If javac is not found, the JDK bin folder 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 demo means folder demo. Running from the wrong directory is the usual “cannot find main class” cause.
  • java.lang is always there — if you import java.lang.System an interviewer may ask why it is unnecessary.
L6

Practice Programs List

  1. List five token kinds and give one example of each from a 5-line program.
  2. Try naming a variable static and record the compiler message.
  3. Write a class with a constant, a local variable, and a print statement, then compile it.
  4. Draw the steps: source → javac → bytecode → class loader → verifier → JVM → output.
  5. Label a JVM sketch: class loaders, heap, stack, method area, JIT, GC.
  6. Create two classes in two files where only one has main and call a method of the other.
  7. Put the public class in package demo, compile from the package root, and run java demo.YourClass.
  8. Add a Javadoc comment above main and generate docs with javadoc if the JDK tool is on PATH.
  9. Break a program once with a missing ; (compile error) and once with / 0 (runtime) and compare the messages.
  10. Print System.getProperty("java.class.path") and explain what the class loader will search.