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
- What Is Java?
- JVM, JRE, and JDK
- The Java Compilation & Execution Process
- Your First Java Program
- The
mainMethod - Java Source File Rules
- Packages
- Imports
- Variables
- Scope
- Access Modifiers
- Static Members
- Initialization Order
- Java 21 Features for Beginners
- Certification Traps
- Common Mistakes
- Interview Questions
- Quick Revision Notes
- 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
| Feature | Meaning (in simple words) |
|---|---|
| Platform Independent | Compiled bytecode runs on Windows, Linux, macOS without changes. |
| Object-Oriented | Everything is organized around classes and objects. |
| Strongly Typed | Every variable has a fixed, declared type. |
| Automatic Memory Management | The Garbage Collector frees unused memory for you. |
| Secure & Robust | No direct pointer access; strict compile-time checks. |
| Multithreaded | Built-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
| Term | Full Form | Purpose | Contains |
|---|---|---|---|
| JVM | Java Virtual Machine | Executes bytecode; provides platform independence | Class loader, verifier, interpreter, JIT, GC |
| JRE | Java Runtime Environment | Provides everything needed to run apps | JVM + core libraries |
| JDK | Java Development Kit | Provides everything needed to develop apps | JRE + 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)
| Stage | Command | Input | Output |
|---|---|---|---|
| Compile | javac Hello.java | .java source | .class bytecode |
| Run | java 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
| Code | Meaning |
|---|---|
public class Hello | Declares 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
| Keyword | Reason |
|---|---|
public | JVM must access it from outside the class. |
static | JVM calls it without creating an object. |
void | It returns nothing to the JVM. |
String[] args | Receives 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.
| Rule | Detail |
|---|---|
| One public top-level class per file | At most one public class/interface/record/enum per .java file. |
| File name must match | If a class is public, the file name must equal that class name + .java. |
| Multiple non-public classes | Allowed in one file. |
package statement | Must be the first statement (excluding comments). |
import statements | Come 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
| Rule | Detail |
|---|---|
| Position | package must be the first non-comment line. |
| Naming convention | All lowercase, reverse-domain style: com.company.project. |
| Default package | A file with no package statement belongs to the unnamed package (avoid in real projects). |
| Folder mapping | Package 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.Accountis 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
| Type | Syntax | Use |
|---|---|---|
| Single-type import | import java.util.List; | Import one class. |
| Wildcard import | import java.util.*; | Import all types in a package (not sub-packages). |
| Static import | import static java.lang.Math.PI; | Import static members directly. |
| Static wildcard | import 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
| Point | Detail |
|---|---|
java.lang auto-imported | String, System, Math, Object need no import. |
| Wildcards are not recursive | import java.util.*; does not import java.util.concurrent.*. |
| No performance cost | Wildcard imports do not make code slower or bigger. |
| Ambiguity = error | Importing 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
| Kind | Where Declared | Default Value? | Lifetime |
|---|---|---|---|
| Local variable | Inside a method/block | ❌ No default (must init before use) | Until block ends |
| Instance variable | In a class, non-static | ✅ Yes (0/false/null) | While object lives |
| Static (class) variable | In a class, with static | ✅ Yes | While class is loaded |
Primitive Types & Default Values
| Type | Size | Default | Example |
|---|---|---|---|
byte | 8-bit | 0 | byte b = 100; |
short | 16-bit | 0 | short s = 1000; |
int | 32-bit | 0 | int i = 42; |
long | 64-bit | 0L | long l = 99L; |
float | 32-bit | 0.0f | float f = 3.14f; |
double | 64-bit | 0.0 | double d = 3.14; |
char | 16-bit | '\u0000' | char c = 'A'; |
boolean | JVM-dependent | false | boolean ok = true; |
Reference types (objects, arrays,
String) default tonull.
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:
| Rule | Detail |
|---|---|
| Local variables only | Cannot be used for fields, method parameters, or return types. |
| Must initialize | var x; is illegal — the compiler needs a value to infer from. |
| Not a keyword | var is a reserved type name; you can still name a variable var (but don't). |
No var x = null | Cannot 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
| Scope | Visible Where |
|---|---|
| Class/Instance | Throughout the class (all instance members). |
| Static | Throughout the class (static and instance contexts). |
| Method/Local | Only inside the method/block where declared. |
| Block | Only inside { } (e.g., loop body, if block). |
| Loop variable | for (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)
| Modifier | Same Class | Same Package | Subclass (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
| Point | Detail |
|---|---|
| Top-level classes | Can only be public or default — not private/protected. |
protected quirk | A subclass in another package can access a protected member only through its own type, not via a parent reference. |
| Encapsulation | Make 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
| Rule | Detail |
|---|---|
| One copy | Shared across all instances. |
| Access | Via class name: Counter.getTotal() (preferred) — or via instance (discouraged). |
| Static methods | Cannot use this or access instance members directly. |
| Static block | Runs once when the class is loaded, in textual order. |
| Loaded lazily | A 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":
| Feature | What It Does | Example |
|---|---|---|
| Single-file launch (11+) | Run .java directly | java Hello.java |
var (10+) | Local type inference | var x = 10; |
| Text Blocks (15+) | Multi-line string literals | see below |
| Records (16+) | Concise immutable data classes | record Point(int x, int y) {} |
Pattern Matching for switch (21) | Cleaner type-based branching | see below |
| Virtual Threads (21) | Lightweight, scalable threads | Thread.ofVirtual().start(...) |
Unnamed Variables _ (21 preview) | Ignore unused values | catch (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 |
|---|---|
| 1 | Two public classes in one file → compile error. |
| 2 | main(String args) (no []) → compiles, but runtime "Main method not found". |
| 3 | Local variables have no default value → using one uninitialized = compile error. |
| 4 | Wildcard import java.util.* does NOT include sub-packages like java.util.concurrent. |
| 5 | package must come before import, which comes before the class. |
| 6 | Accessing a non-static field from static main → compile error. |
| 7 | var x = null; → compile error (cannot infer type). |
| 8 | protected members in another package are accessed only via the subclass's own reference. |
| 9 | Static init runs once in source order; don't assume it follows method-call order. |
| 10 | import cannot import a package "as a whole"; you import types (or static members). |
| 11 | A top-level class cannot be private or protected. |
| 12 | Ambiguous wildcard imports (java.util.Date vs java.sql.Date) require the FQN. |
16. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| File name ≠ public class name | Name the file exactly ClassName.java. |
Running with .class: java Hello.class | Use the class name only: java Hello. |
Forgetting static on main | Always public static void main(String[] args). |
| Using a local var before assigning it | Initialize it first. |
Putting import above package | Order is package → import → class. |
Calling instance methods from static context | Create an object first, or make members static. |
Confusing == and .equals() for objects | Use .equals() for value comparison. |
| Assuming wildcard imports slow things down | They don't — purely a compile-time convenience. |
| Naming packages with uppercase | Use 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.java→File.class;java Fileruns it (no.class).- Java 11+:
java File.javaruns source directly;jshellis the REPL. - One public type per file; file name = public class name.
- Source order:
package→import→ type declaration. main:public static void main(String[] args).java.langis 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; nonull.- Access:
private< default <protected<public. static= one shared copy at class level; nothis.- 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.