MindIQ Academy

01 - Getting Started With Java

A complete beginner-to-advanced guide to Java fundamentals, aligned with the Oracle Certified Professional: Java SE 21 Developer (1Z0-830) exam objectives.


Table of Contents

  1. What Is Java?
  2. JVM, JRE, and JDK
  3. The Java Compilation & Execution Process
  4. Your First Java Program
  5. The main Method
  6. Java Source File Rules
  7. Packages
  8. Imports
  9. Variables
  10. Scope
  11. Access Modifiers
  12. Static Members
  13. Initialization Order
  14. Java 21 Features for Beginners
  15. Certification Traps
  16. Common Mistakes
  17. Interview Questions
  18. Quick Revision Notes
  19. One-Page Cheat Sheet

1. What Is Java?

Java is a high-level, object-oriented, platform-independent programming language. Its famous promise is "Write Once, Run Anywhere" (WORA) — you compile your code once into bytecode, and it runs on any device that has a Java Virtual Machine.

Key Characteristics

FeatureMeaning (in simple words)
Platform IndependentCompiled bytecode runs on Windows, Linux, macOS without changes.
Object-OrientedEverything is organized around classes and objects.
Strongly TypedEvery variable has a fixed, declared type.
Automatic Memory ManagementThe Garbage Collector frees unused memory for you.
Secure & RobustNo direct pointer access; strict compile-time checks.
MultithreadedBuilt-in support for concurrent execution.

2. JVM, JRE, and JDK

These three are the most confused terms for beginners. Here is the simplest way to remember them:

JDK = tools to develop + JRE = things to run + JVM = the engine that executes.

Diagram: How They Nest

+---------------------------------------------------------------+
|  JDK (Java Development Kit)                                    |
|  Tools to WRITE and BUILD Java programs                        |
|  e.g. javac (compiler), jar, javadoc, jshell, jdb             |
|                                                               |
|   +-------------------------------------------------------+   |
|   |  JRE (Java Runtime Environment)                       |   |
|   |  Things needed to RUN Java programs                   |   |
|   |  e.g. core libraries (java.lang, java.util ...)       |   |
|   |                                                       |   |
|   |    +-----------------------------------------------+  |   |
|   |    |  JVM (Java Virtual Machine)                   |  |   |
|   |    |  The ENGINE that executes bytecode            |  |   |
|   |    |  - Class Loader                               |  |   |
|   |    |  - Bytecode Verifier                          |  |   |
|   |    |  - Interpreter + JIT Compiler                 |  |   |
|   |    |  - Garbage Collector                          |  |   |
|   |    +-----------------------------------------------+  |   |
|   +-------------------------------------------------------+   |
+---------------------------------------------------------------+

Comparison Table

TermFull FormPurposeContains
JVMJava Virtual MachineExecutes bytecode; provides platform independenceClass loader, verifier, interpreter, JIT, GC
JREJava Runtime EnvironmentProvides everything needed to run appsJVM + core libraries
JDKJava Development KitProvides everything needed to develop appsJRE + compiler + dev tools

Note (Java 11+): Oracle no longer ships a standalone JRE for download. The JDK is the standard distribution, and you create custom runtimes with jlink.

The JVM Internally

Source.java --javac--> Source.class (bytecode) --> JVM
                                                    |
        +-------------------+-------------------+----+
        |                   |                   |
   Class Loader      Bytecode Verifier    Execution Engine
   (loads .class)    (security check)     (Interpreter + JIT)
                                                |
                                          Native Machine Code
  • Interpreter: Executes bytecode line-by-line (fast startup, slower run).
  • JIT (Just-In-Time) Compiler: Compiles "hot" (frequently used) code to native machine code for speed.

3. The Java Compilation & Execution Process

Step-by-Step Flow

  1. WRITE            2. COMPILE              3. RUN
+-----------+      +---------------+      +-------------------+
| Hello.java| ---> | javac Hello.java| --> | java Hello        |
|  (source) |      |               |      |                   |
+-----------+      +---------------+      +-------------------+
                          |                        |
                          v                        v
                   Hello.class               Output on console
                   (bytecode)
StageCommandInputOutput
Compilejavac Hello.java.java source.class bytecode
Runjava Hello.class (class name, no .class)Program output

Single-File Source-Code Programs (Java 11+)

Since Java 11 you can run a source file without compiling it first:

java Hello.java

The JVM compiles it in memory and runs it immediately — great for learning and scripting.

jshell — The REPL (Java 9+)

jshell
jshell> int x = 5
x ==> 5
jshell> System.out.println(x * 2)
10

jshell lets you experiment with snippets without writing a full class.


4. Your First Java Program

// File: Hello.java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, Java 21!");
    }
}

Compile and run:

javac Hello.java     # produces Hello.class
java Hello           # prints: Hello, Java 21!

What Each Part Means

CodeMeaning
public class HelloDeclares a class named Hello (must match file name).
public static void main(String[] args)Entry point the JVM calls to start the program.
System.out.println(...)Prints a line to standard output.

5. The main Method

The main method is the entry point — the JVM looks for this exact signature to start execution.

The Canonical Signature

public static void main(String[] args) { }

Valid Variations

public static void main(String[] args)      // standard
public static void main(String... args)     // varargs - VALID
static public void main(String[] args)      // modifier order can swap
public static void main(String args[])      // C-style array - VALID

Why Each Keyword Matters

KeywordReason
publicJVM must access it from outside the class.
staticJVM calls it without creating an object.
voidIt returns nothing to the JVM.
String[] argsReceives command-line arguments.

Trap: Compiles But Won't Run

public class Demo {
    public static void main(String args) {   // String, not String[]
        System.out.println("Hi");
    }
}

This compiles but throws at runtime:

Error: Main method not found in class Demo

Because the signature does not match main(String[]), the JVM cannot find a valid entry point.


6. Java Source File Rules

These rules are heavily tested on the exam.

RuleDetail
One public top-level class per fileAt most one public class/interface/record/enum per .java file.
File name must matchIf a class is public, the file name must equal that class name + .java.
Multiple non-public classesAllowed in one file.
package statementMust be the first statement (excluding comments).
import statementsCome after package, before any type declaration.

Example

// File: Calculator.java
package com.app.math;          // 1. package (first)

import java.util.List;         // 2. imports

public class Calculator { }    // 3. public type (name matches file)

class Helper { }               // non-public, allowed in same file

Trap

// File: Foo.java
public class Foo { }
public class Bar { }   // COMPILE ERROR: two public classes in one file

7. Packages

A package is a namespace that groups related classes — like folders for your code. They prevent naming conflicts and control access.

Declaring a Package

package com.example.banking;

public class Account { }

Diagram: Package = Folder Structure

src/
└── com/
    └── example/
        └── banking/
            └── Account.java   ->   package com.example.banking;

Rules

RuleDetail
Positionpackage must be the first non-comment line.
Naming conventionAll lowercase, reverse-domain style: com.company.project.
Default packageA file with no package statement belongs to the unnamed package (avoid in real projects).
Folder mappingPackage name maps to directory path.

Compiling Into Packages

javac -d out src/com/example/banking/Account.java
java -cp out com.example.banking.Account

Fully Qualified Name (FQN): com.example.banking.Account is the unique identity of the class.


8. Imports

import lets you use a class by its short name instead of its fully qualified name.

Types of Imports

TypeSyntaxUse
Single-type importimport java.util.List;Import one class.
Wildcard importimport java.util.*;Import all types in a package (not sub-packages).
Static importimport static java.lang.Math.PI;Import static members directly.
Static wildcardimport static java.lang.Math.*;Import all static members.

Example

import java.util.List;
import java.util.ArrayList;
import static java.lang.Math.max;

public class Demo {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        System.out.println(max(10, 20));   // no Math. prefix needed
    }
}

Important Rules & Traps

PointDetail
java.lang auto-importedString, System, Math, Object need no import.
Wildcards are not recursiveimport java.util.*; does not import java.util.concurrent.*.
No performance costWildcard imports do not make code slower or bigger.
Ambiguity = errorImporting two classes with the same name (java.util.Date & java.sql.Date) via wildcards forces you to use the FQN.
You cannot import "a package itself"You import types, not packages.

Trap: Ambiguous Import

import java.util.*;
import java.sql.*;

Date d;   // COMPILE ERROR: Date is ambiguous (java.util.Date vs java.sql.Date)

9. Variables

A variable is a named container that stores a value of a specific type.

The Three Kinds of Variables

KindWhere DeclaredDefault Value?Lifetime
Local variableInside a method/block❌ No default (must init before use)Until block ends
Instance variableIn a class, non-static✅ Yes (0/false/null)While object lives
Static (class) variableIn a class, with static✅ YesWhile class is loaded

Primitive Types & Default Values

TypeSizeDefaultExample
byte8-bit0byte b = 100;
short16-bit0short s = 1000;
int32-bit0int i = 42;
long64-bit0Llong l = 99L;
float32-bit0.0ffloat f = 3.14f;
double64-bit0.0double d = 3.14;
char16-bit'\u0000'char c = 'A';
booleanJVM-dependentfalseboolean ok = true;

Reference types (objects, arrays, String) default to null.

The var Keyword (Local Variable Type Inference, Java 10+)

var message = "Hello";      // inferred as String
var count = 10;             // inferred as int
var list = new ArrayList<String>();  // inferred as ArrayList<String>

Rules for var:

RuleDetail
Local variables onlyCannot be used for fields, method parameters, or return types.
Must initializevar x; is illegal — the compiler needs a value to infer from.
Not a keywordvar is a reserved type name; you can still name a variable var (but don't).
No var x = nullCannot infer type from null alone.

Trap: Local Variable Not Initialized

public void test() {
    int x;
    System.out.println(x);   // COMPILE ERROR: variable x might not have been initialized
}

Instance/static variables would print 0 here — but local variables have no default.


10. Scope

Scope = the region of code where a variable is visible and usable.

Diagram: Scope Levels

class Box {                         <-- class scope (fields)
    int instanceField;              visible to all instance methods

    static int staticField;         <-- visible to all (static) methods

    void method(int param) {        <-- param: method scope
        int local = 5;              <-- block/method scope
        if (local > 0) {
            int inner = 10;         <-- visible only inside this if-block
        }
        // 'inner' NOT visible here
    }
    // 'local', 'param' NOT visible here
}

Scope Rules

ScopeVisible Where
Class/InstanceThroughout the class (all instance members).
StaticThroughout the class (static and instance contexts).
Method/LocalOnly inside the method/block where declared.
BlockOnly inside { } (e.g., loop body, if block).
Loop variablefor (int i...)i is visible only inside the loop.

Trap: Variable Shadowing

public class Shadow {
    int x = 10;                 // instance variable

    void show() {
        int x = 20;             // local variable shadows the instance one
        System.out.println(x);        // 20 (local wins)
        System.out.println(this.x);   // 10 (use 'this' to reach the field)
    }
}

11. Access Modifiers

Access modifiers control who can see/use a class, method, or field.

The Four Levels (Most → Least Restrictive)

ModifierSame ClassSame PackageSubclass (diff package)Everywhere
private
(default/package-private)
protected
public

"default" means no modifier keyword written at all — also called package-private.

Diagram: Visibility Radius

public      ███████████████████████  (whole world)
protected   ███████████████░░░░░░░░  (package + subclasses)
default     ██████████░░░░░░░░░░░░░  (package only)
private     ████░░░░░░░░░░░░░░░░░░░  (this class only)

Example

public class Account {
    private double balance;        // hidden — encapsulation
    protected String owner;        // subclasses can use
    int branchCode;                // package-private
    public String accountId;       // everyone

    public double getBalance() {   // controlled access (getter)
        return balance;
    }
}

Rules & Traps

PointDetail
Top-level classesCan only be public or defaultnot private/protected.
protected quirkA subclass in another package can access a protected member only through its own type, not via a parent reference.
EncapsulationMake fields private, expose public getters/setters.

12. Static Members

static members belong to the class itself, not to any individual object. There is exactly one copy, shared by all instances.

Diagram: Static vs Instance

              class Counter
        +-----------------------+
        | static int total = 0  |  <-- ONE shared copy (class-level)
        +-----------------------+
              /         \
       obj1  /           \  obj2
   +------------+    +------------+
   | int id     |    | int id     |  <-- each object has its OWN copy
   +------------+    +------------+

Static Variables, Methods, and Blocks

public class Counter {
    static int total = 0;        // shared by all objects
    int id;                      // unique per object

    static { System.out.println("Static block runs once"); }  // class init

    Counter() {
        total++;                 // affects the shared counter
        id = total;
    }

    static int getTotal() {      // static method
        return total;            // can access static members only
    }
}

Rules

RuleDetail
One copyShared across all instances.
AccessVia class name: Counter.getTotal() (preferred) — or via instance (discouraged).
Static methodsCannot use this or access instance members directly.
Static blockRuns once when the class is loaded, in textual order.
Loaded lazilyA class is initialized the first time it is actively used.

Trap: Accessing Instance Members From Static Context

public class Demo {
    int x = 5;

    public static void main(String[] args) {
        System.out.println(x);   // COMPILE ERROR: non-static field x cannot
                                 // be referenced from a static context
    }
}

Fix: create an object — new Demo().x — or make x static.


13. Initialization Order

This is one of the most-tested topics. Know it cold.

The Exact Order

WHEN A CLASS IS FIRST LOADED (happens once):
  1. Static variables and static initializer blocks
     -> executed in the ORDER they appear in the source

WHEN AN OBJECT IS CREATED (every 'new'):
  2. Instance variables and instance initializer blocks
     -> executed in the ORDER they appear in the source
  3. Constructor body

Summary: Static (once) → Instance fields/blocks (each object) → Constructor. With inheritance: Parent static → Child static → Parent instance + constructor → Child instance + constructor.

Example: Trace the Output

public class InitDemo {
    static int s = log("1: static field");
    static { log("2: static block"); }

    int i = log("4: instance field");
    { log("5: instance block"); }

    InitDemo() {
        log("6: constructor");
    }

    static int log(String msg) {
        System.out.println(msg);
        return 0;
    }

    public static void main(String[] args) {
        log("3: main starts");
        new InitDemo();
    }
}

Output:

1: static field
2: static block
3: main starts
4: instance field
5: instance block
6: constructor

Order With Inheritance

class Parent {
    static { System.out.println("P-static"); }
    { System.out.println("P-instance"); }
    Parent() { System.out.println("P-ctor"); }
}

class Child extends Parent {
    static { System.out.println("C-static"); }
    { System.out.println("C-instance"); }
    Child() { System.out.println("C-ctor"); }
}

// new Child() prints:
// P-static
// C-static
// P-instance
// P-ctor
// C-instance
// C-ctor

Rule: All static initialization (parent then child) happens first and only once. Then for each object: parent instance init + parent constructor, then child instance init + child constructor.


14. Java 21 Features for Beginners

Java 21 is a Long-Term Support (LTS) release. A few beginner-friendly highlights relevant to "getting started":

FeatureWhat It DoesExample
Single-file launch (11+)Run .java directlyjava Hello.java
var (10+)Local type inferencevar x = 10;
Text Blocks (15+)Multi-line string literalssee below
Records (16+)Concise immutable data classesrecord Point(int x, int y) {}
Pattern Matching for switch (21)Cleaner type-based branchingsee below
Virtual Threads (21)Lightweight, scalable threadsThread.ofVirtual().start(...)
Unnamed Variables _ (21 preview)Ignore unused valuescatch (Exception _)

Text Blocks

String json = """
        {
            "name": "Java",
            "version": 21
        }
        """;

Pattern Matching for switch (Java 21)

static String describe(Object obj) {
    return switch (obj) {
        case Integer i -> "Integer: " + i;
        case String s  -> "String of length " + s.length();
        case null      -> "It is null";
        default        -> "Something else";
    };
}

Record (a one-line data class)

record Point(int x, int y) { }   // gets constructor, getters, equals, hashCode, toString

15. Certification Traps

The 1Z0-830 exam loves these "gotchas." Watch for them.

#Trap
1Two public classes in one file → compile error.
2main(String args) (no []) → compiles, but runtime "Main method not found".
3Local variables have no default value → using one uninitialized = compile error.
4Wildcard import java.util.* does NOT include sub-packages like java.util.concurrent.
5package must come before import, which comes before the class.
6Accessing a non-static field from static main → compile error.
7var x = null; → compile error (cannot infer type).
8protected members in another package are accessed only via the subclass's own reference.
9Static init runs once in source order; don't assume it follows method-call order.
10import cannot import a package "as a whole"; you import types (or static members).
11A top-level class cannot be private or protected.
12Ambiguous wildcard imports (java.util.Date vs java.sql.Date) require the FQN.

16. Common Mistakes

MistakeCorrect Approach
File name ≠ public class nameName the file exactly ClassName.java.
Running with .class: java Hello.classUse the class name only: java Hello.
Forgetting static on mainAlways public static void main(String[] args).
Using a local var before assigning itInitialize it first.
Putting import above packageOrder is packageimport → class.
Calling instance methods from static contextCreate an object first, or make members static.
Confusing == and .equals() for objectsUse .equals() for value comparison.
Assuming wildcard imports slow things downThey don't — purely a compile-time convenience.
Naming packages with uppercaseUse all-lowercase package names.

17. Interview Questions

Q1. What is the difference between JDK, JRE, and JVM? JVM executes bytecode; JRE = JVM + core libraries (to run apps); JDK = JRE + development tools like javac (to build apps).

Q2. Why is Java platform independent? Because javac compiles source to platform-neutral bytecode, which any platform's JVM can execute.

Q3. What happens if you write two public classes in one file? Compile error — only one public top-level type is allowed per file.

Q4. Can the main method be overloaded? Yes, but the JVM only calls the one with signature public static void main(String[] args).

Q5. What is the default value of a local variable? There is none — local variables must be explicitly initialized before use.

Q6. Difference between static and instance variables? Static variables have one shared copy at class level; instance variables get a separate copy per object.

Q7. What is the initialization order in Java? Static fields/blocks (once, in order) → instance fields/blocks (per object, in order) → constructor. With inheritance, parent before child.

Q8. Does import java.util.*; import sub-packages? No. Wildcards are not recursive; java.util.concurrent is not included.

Q9. What are the access modifiers and their visibility? private (class), default/package-private (package), protected (package + subclasses), public (everywhere).

Q10. What is the var keyword and where can it be used? Local variable type inference (Java 10+) — usable only for local variables that are initialized; not for fields, parameters, or return types.

Q11. Can a static method access instance variables? No, not directly — it has no this. It must use an object reference.

Q12. What is a package and why use it? A namespace grouping related types; prevents name clashes and supports access control.


18. Quick Revision Notes

  • JVM runs bytecode; JRE = JVM + libs; JDK = JRE + tools.
  • javac File.javaFile.class; java File runs it (no .class).
  • Java 11+: java File.java runs source directly; jshell is the REPL.
  • One public type per file; file name = public class name.
  • Source order: packageimport → type declaration.
  • main: public static void main(String[] args).
  • java.lang is auto-imported; wildcard imports are not recursive.
  • Local vars: no default, must initialize. Fields: default to 0/false/null.
  • var = local type inference; needs an initializer; no null.
  • Access: private < default < protected < public.
  • static = one shared copy at class level; no this.
  • Init order: static (once) → instance fields/blocks → constructor; parent before child.
  • Java 21 LTS: text blocks, records, pattern matching for switch, virtual threads.

19. One-Page Cheat Sheet

============================ JAVA QUICK CHEAT SHEET ============================

COMPILE & RUN
  javac Hello.java        -> Hello.class
  java  Hello             -> run (NO .class extension)
  java  Hello.java        -> run source directly (Java 11+)
  jshell                  -> interactive REPL (Java 9+)

ENTRY POINT
  public static void main(String[] args) { ... }
  (String... args and String args[] are also valid)

FILE RULES
  - At most ONE public top-level type per file
  - public class name MUST equal file name
  - order: package; -> import; -> class

PACKAGES & IMPORTS
  package com.app.module;            // first non-comment line
  import java.util.List;             // single type
  import java.util.*;                // wildcard (NOT recursive)
  import static java.lang.Math.PI;   // static import
  java.lang.* is auto-imported

VARIABLES                         DEFAULTS
  local    -> NO default (must init)   int=0   long=0L   double=0.0
  instance -> defaults applied         boolean=false     char='\u0000'
  static   -> defaults applied         reference (objects) = null
  var x = 10;  // local inference only; needs initializer; no null

ACCESS MODIFIERS         class  package  subclass  world
  private                  Y      -        -        -
  (default)                Y      Y        -        -
  protected                Y      Y        Y        -
  public                   Y      Y        Y        Y
  (top-level class: only public or default)

STATIC
  - one shared copy at class level
  - access via ClassName.member
  - static methods: no 'this', no direct instance access

INITIALIZATION ORDER
  1. static fields + static blocks   (ONCE, in source order)
  2. instance fields + init blocks   (per object, in source order)
  3. constructor body
  inheritance: Parent static -> Child static
               -> Parent instance+ctor -> Child instance+ctor

JAVA 21 (LTS) HIGHLIGHTS
  text blocks  """ ... """      records   record P(int x){}
  switch patterns  case Integer i -> ...   virtual threads Thread.ofVirtual()

TOP TRAPS
  * two public classes in one file        -> compile error
  * main(String args) [no []]             -> runtime "main not found"
  * uninitialized local variable          -> compile error
  * wildcard import is NOT recursive
  * instance access from static main      -> compile error
===============================================================================

End of 01 - Getting Started With Java.