Java Basics
How Java code is structured and run — the JDK, compiling and running, primitive vs reference types, strings, arrays, control flow, methods, packages, and the gotchas that trip up newcomers.
Java is a statically typed, object-oriented, garbage-collected language that compiles to bytecode and runs on the Java Virtual Machine (JVM). "Write once, run anywhere": the same .class files run on any OS with a JVM. It powers a huge share of back-end systems, Android, big-data tools (Kafka, Spark, Elasticsearch) and enterprise software.
From source to running program
// Hello.java — the public class name must match the file name
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, " + (args.length > 0 ? args[0] : "world"));
}
}javac Hello.java # produces Hello.class
java Hello Ada # Hello, Ada
java Hello.java Ada # Java 11+: compile and run a single file in one step- JDK (Development Kit) = compiler, tools and the runtime. JRE = just the runtime (now bundled). Use an LTS release (17, 21, 25).
- Real projects use a build tool: Maven (
pom.xml) or Gradle (build.gradle.kts) for dependencies, compiling, testing and packaging into JARs. jshellis an interactive REPL for experimenting.
Primitive vs reference types
Java has 8 primitive types, stored directly as values, and everything else is a reference to an object on the heap.
| Type | Size | Range / notes | Default |
|---|---|---|---|
byte | 8-bit | −128 to 127 | 0 |
short | 16-bit | −32,768 to 32,767 | 0 |
int | 32-bit | about ±2.1 billion | 0 |
long | 64-bit | about ±9.2 × 10¹⁸ (suffix L) | 0L |
float | 32-bit | IEEE 754, ~7 digits (suffix f) | 0.0f |
double | 64-bit | IEEE 754, ~15–16 digits | 0.0 |
char | 16-bit | One UTF-16 code unit | '\u0000' |
boolean | — | true / false | false |
Each primitive has a wrapper class (Integer, Long, Double…) used in collections and generics. Java converts automatically (autoboxing/unboxing), which has costs and traps:
Integer a = 127, b = 127;
System.out.println(a == b); // true (cached small Integers: -128..127)
Integer c = 128, d = 128;
System.out.println(c == d); // false (different objects!) — compare with equals()
Integer n = null;
int x = n; // NullPointerException on unboxingInteger overflow and floating point
int big = Integer.MAX_VALUE;
System.out.println(big + 1); // -2147483648: silent wrap-around
Math.addExact(big, 1); // throws ArithmeticException instead
System.out.println(0.1 + 0.2); // 0.30000000000000004
new BigDecimal("0.1").add(new BigDecimal("0.2")); // 0.3 — use BigDecimal (or long cents) for money
System.out.println(7 / 2); // 3 (integer division)
System.out.println(-7 % 3); // -1 (remainder takes the dividend's sign)Variables and var
int count = 0; // explicit type
final double RATE = 0.07; // final: can't be reassigned
var names = new ArrayList<String>(); // Java 10+: local type inference (still statically typed)Strings
String is an immutable object. Every "modification" creates a new string.
String s = "Hello";
s.length(); // 5
s.charAt(1); // 'e'
s.substring(1, 4); // "ell"
s.toUpperCase(); // "HELLO" (s itself unchanged)
s.contains("ell"); // true
"a,b,c".split(","); // ["a","b","c"]
String.join("-", "a", "b"); // "a-b"
" hi ".strip(); // "hi"
"%s is %d".formatted("Ada", 36); // "Ada is 36"
// Text blocks (Java 15+)
String json = """
{"name": "Ada", "age": 36}
""";Concatenating in a loop creates many temporary strings — use StringBuilder:
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append(i).append(',');
String result = sb.toString();Arrays
Fixed-length, zero-indexed, with a length field. For resizable lists use ArrayList (Collections).
int[] nums = {5, 3, 8};
int[] zeros = new int[10]; // filled with defaults (0)
int[][] grid = new int[3][4]; // 3 rows, 4 columns
Arrays.sort(nums); // [3, 5, 8]
Arrays.toString(nums); // "[3, 5, 8]"
Arrays.fill(zeros, -1);
int[] copy = Arrays.copyOf(nums, 5); // [3, 5, 8, 0, 0]
nums[3] = 1; // ArrayIndexOutOfBoundsExceptionControl flow
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else grade = 'C';
for (int i = 0; i < n; i++) { ... }
for (String name : names) { ... } // enhanced for
while (queue.size() > 0) { ... }
do { line = read(); } while (line != null);
// Labeled break out of nested loops
outer:
for (int[] row : grid)
for (int v : row)
if (v < 0) break outer;
// Switch expressions (Java 14+): no fall-through, returns a value
String type = switch (day) {
case SATURDAY, SUNDAY -> "weekend";
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "weekday";
};Methods
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; } // overloading
static int sum(int... values) { // varargs
int total = 0;
for (int v : values) total += v;
return total;
}Packages, imports and access modifiers
package com.example.billing; // matches directory com/example/billing/
import java.util.List;
import java.time.*; // all public types in java.time
import static java.lang.Math.max; // static import| Modifier | Class | Package | Subclass | Everywhere |
|---|---|---|---|---|
private | ✓ | |||
| (none) package-private | ✓ | ✓ | ||
protected | ✓ | ✓ | ✓ | |
public | ✓ | ✓ | ✓ | ✓ |
Reading input
import java.util.Scanner;
try (Scanner in = new Scanner(System.in)) {
int n = in.nextInt();
String name = in.next();
}
// For competitive programming, BufferedReader is much faster than Scanner- javac compiles to bytecode; the JVM interprets and JIT-compiles it.
- 8 primitives (stored by value) plus references to heap objects; wrappers autobox.
- Use equals() for objects; == compares identity. Small Integer caching makes == misleading.
- int overflow wraps silently; use long, Math.addExact or BigDecimal where it matters.
- Strings are immutable; build with StringBuilder in loops.
- Java is pass-by-value — for objects, the reference is copied.
QWhy is String immutable in Java?medium
Immutability makes strings safe to share across threads without synchronisation, lets the JVM intern literals in a string pool so identical strings share memory, allows the hash code to be cached (fast HashMap keys), and prevents security issues where a validated value (a file path or class name) could be changed after the check.
QIs Java pass-by-value or pass-by-reference?easy
Always pass-by-value. For object arguments the value passed is a copy of the reference, so the method can mutate the shared object but cannot make the caller's variable refer to a different object.