Java
Updated: May 21, 2026Categories: Languages, Backend, Mobile, Frontend
Printed from:
Java Cheatsheet
Language Overview
Java is a robust, object-oriented, statically-typed programming language originally developed by Sun Microsystems and now stewarded by Oracle. The current Long-Term Support (LTS) release is Java 21 (with Java 17 still in widespread LTS use, and Java 25 scheduled as the next LTS in September 2025). Key characteristics include:
- Platform independence ("Write Once, Run Anywhere") via the JVM
- Strong static typing with limited local type inference
- Automatic memory management (Garbage Collection — G1 by default, ZGC and Shenandoah for low-latency)
- Enterprise-level application development
- Used in web, mobile, desktop, cloud-native, and big-data applications
- Six-month release cadence, with LTS releases every two years (11, 17, 21, 25…)
Basic Syntax
Java
12345678910111213141516171819// Single-line comment
/* Multi-line comment */
// Traditional program structure
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
// Java 21+: Unnamed classes and instance main methods (preview)
// File: HelloWorld.java
void main() {
System.out.println("Hello, World!");
}
// Semicolons are required to end statements
// Curly braces {} define code blocks
Data Types
Primitive Types
Java
12345678910111213141516// Integers
byte byteVar = 127; // 8-bit signed
short shortVar = 32_767; // 16-bit signed (underscores allowed in literals)
int intVar = 2_147_483_647; // 32-bit signed
long longVar = 9_223_372_036_854_775_807L; // 64-bit signed
// Floating-point
float floatVar = 3.14f; // 32-bit IEEE 754
double doubleVar = 3.14159; // 64-bit IEEE 754
// Character
char charVar = 'A'; // 16-bit Unicode code unit
// Boolean
boolean boolVar = true; // true or false
Collection Types
Java
1234567891011121314151617181920212223// Lists
List<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
// Sets
Set<Integer> hashSet = new HashSet<>();
hashSet.add(1);
hashSet.add(2);
// Maps
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("key", 42);
// Queues / Deques (prefer ArrayDeque over LinkedList)
Deque<String> queue = new ArrayDeque<>();
queue.add("First");
// Immutable factory methods (Java 9+)
List<Integer> nums = List.of(1, 2, 3);
Set<String> tags = Set.of("a", "b");
Map<String, Integer> scores = Map.of("a", 1, "b", 2);
Variables and Constants
Java
1234567891011121314151617// Variable declaration
int age = 30; // Mutable variable
final int MAX_SIZE = 100; // Constant (cannot be reassigned)
// Type inference for local variables (Java 10+)
var dynamicVar = "Hello"; // Inferred as String at compile time
var list = new ArrayList<String>(); // Inferred as ArrayList<String>
// Scope
public class ScopeExample {
private int instanceVar; // Instance field
public void method() {
int localVar = 10; // Method-local variable
}
}
Operators
Arithmetic Operators
Java
1234567int a = 10, b = 5;
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
int div = a / b; // Integer division
int mod = a % b; // Modulus
Comparison Operators
Java
12345boolean equal = (a == b); // Equal
boolean notEqual = (a != b); // Not equal
boolean greater = (a > b); // Greater than
boolean greaterEqual = (a >= b); // Greater than or equal
Logical Operators
Java
12345boolean x = true, y = false;
boolean andResult = x && y; // Short-circuit AND
boolean orResult = x || y; // Short-circuit OR
boolean notResult = !x; // NOT
Control Structures
Conditional Statements
Java
123456789101112131415161718192021222324252627282930// If-Else
if (condition) {
// Code if true
} else if (anotherCondition) {
// Alternative
} else {
// Default
}
// Ternary Operator
int result = condition ? valueIfTrue : valueIfFalse;
// Switch expression with arrow labels (standard since Java 14)
String label = switch (value) {
case 1 -> "One";
case 2, 3 -> "Two or Three";
default -> "Other";
};
// Pattern matching for switch (standard since Java 21)
String describe(Object o) {
return switch (o) {
case Integer i when i > 0 -> "positive int " + i;
case Integer i -> "non-positive int " + i;
case String s -> "string: " + s;
case null -> "null";
default -> "unknown";
};
}
Loops
Java
123456789101112131415161718192021222324252627// For Loop
for (int i = 0; i < 10; i++) {
// ...
}
// Enhanced For (For-Each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
// While Loop
while (condition) {
// ...
}
// Do-While Loop
do {
// Executes at least once
} while (condition);
// Break and Continue
for (int i = 0; i < 10; i++) {
if (i == 5) break; // Exit loop
if (i % 2 == 0) continue; // Skip iteration
}
Functions
Java
123456789101112131415161718192021222324// Basic Method
public int add(int a, int b) {
return a + b;
}
// Method with Multiple Parameters
public void printDetails(String name, int age) {
System.out.println(name + " is " + age + " years old");
}
// Static Method
public static void staticMethod() {
// Called on the class, not an instance
}
// Lambda Expressions (Java 8+)
interface MathOperation {
int operate(int a, int b);
}
MathOperation addition = (a, b) -> a + b;
// Method references
Function<String, Integer> len = String::length;
Object-Oriented Programming
Classes and Objects
Java
123456789101112131415public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
Person person = new Person("John", 30);
Records (standard since Java 16)
Java
123456// Immutable data carrier — auto-generates constructor, accessors, equals, hashCode, toString
public record Point(int x, int y) {}
Point p = new Point(3, 4);
int x = p.x();
Inheritance
Java
12345678910111213141516171819public class Animal {
protected String name;
public void eat() {
System.out.println("Animal is eating");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("Dog is eating");
}
public void bark() {
System.out.println("Woof!");
}
}
Interfaces and Abstract Classes
Java
123456789101112131415161718// Interface (default & static methods allowed since Java 8; private methods since Java 9)
public interface Drawable {
void draw(); // implicitly public abstract
default void describe() { // default method
System.out.println("A drawable thing");
}
}
// Abstract Class
public abstract class Shape {
abstract double calculateArea();
public void display() {
System.out.println("This is a shape");
}
}
Sealed Classes (standard since Java 17)
Java
12345public sealed interface Shape permits Circle, Square, Triangle {}
public record Circle(double radius) implements Shape {}
public record Square(double side) implements Shape {}
public record Triangle(double base, double height) implements Shape {}
Pattern Matching for instanceof (standard since Java 16)
Java
1234if (obj instanceof String s && !s.isBlank()) {
System.out.println(s.toUpperCase());
}
Error Handling
Java
1234567891011121314151617181920212223// Try-Catch
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
// Always runs
}
// Multi-catch
try {
// ...
} catch (IOException | SQLException e) {
e.printStackTrace();
}
// Throwing Exceptions
public void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
File I/O
Java
123456789101112131415161718192021222324import java.io.*;
import java.nio.file.*;
import java.util.List;
// Classic Buffered I/O (try-with-resources)
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Modern NIO.2 (preferred)
Path path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
Files.writeString(Path.of("output.txt"), "Hello, World!");
// Streaming a large file
try (var stream = Files.lines(path)) {
stream.forEach(System.out::println);
}
Stream API (Java 8+)
Java
12345678910111213141516List<String> names = List.of("Alice", "Bob", "Charlie");
// Filter and Collect (toList() since Java 16 — preferred over Collectors.toList())
List<String> filtered = names.stream()
.filter(n -> n.startsWith("A"))
.toList();
// Map and Reduce
int totalLength = names.stream()
.mapToInt(String::length)
.sum();
// Grouping
Map<Integer, List<String>> byLength = names.stream()
.collect(Collectors.groupingBy(String::length));
Text Blocks (standard since Java 15)
Java
12String json = """
{
"name": "Alice",
"age": 30
}
""";
Concurrency
Virtual Threads (standard since Java 21)
Java
123456// Lightweight threads scheduled by the JVM — great for high-concurrency I/O
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> fetch("https://example.com/a"));
executor.submit(() -> fetch("https://example.com/b"));
} // auto-shutdown
CompletableFuture
Java
12345CompletableFuture .supplyAsync(() -> fetchData()) .thenApply(String::toUpperCase) .thenAccept(System.out::println);
Common Libraries and Frameworks
Standard Library
java.util: Collections,Optional, concurrency utilitiesjava.time: Modern Date/Time API (LocalDate,Instant,Duration)java.io/java.nio.file: I/O and modern file APIsjava.util.concurrent: Executors, virtual threads, atomic typesjava.net.http: Built-inHttpClient(Java 11+)
Popular Frameworks
- Spring Framework / Spring Boot 3 (requires Java 17+): Dependency injection, web, microservices
- Jakarta EE 10/11: Enterprise APIs (note the
javax.*→jakarta.*package rename) - Hibernate / Jakarta Persistence: ORM
- Quarkus / Micronaut / Helidon: Cloud-native, GraalVM-friendly frameworks
- JUnit 5 (Jupiter): Unit testing
- Mockito: Mocking
- Apache Commons / Guava: Utility libraries
Build Tools
Bash
123456789# Maven
mvn clean install # Build and install project
mvn test # Run tests
mvn wrapper:wrapper # Generate ./mvnw wrapper
# Gradle (Kotlin or Groovy DSL)
./gradlew build # Build project
./gradlew test # Run tests
Best Practices
- Follow Java naming conventions (camelCase for variables/methods, PascalCase for types)
- Use meaningful variable and method names
- Keep methods small and focused
- Prefer composition over inheritance
- Use interfaces (and sealed hierarchies) to define contracts
- Handle exceptions meaningfully — avoid swallowing them
- Use try-with-resources for any
AutoCloseable - Leverage generics for type safety; avoid raw types
- Prefer immutability — use
final, records, and unmodifiable collections - Prefer
java.timeover the legacyDate/CalendarAPIs - Use
Optionalfor return values that may be absent — not for fields or parameters - Target a current LTS (Java 17 or 21); avoid EOL versions (8, 11 are in extended support only)
Testing with JUnit 5
Java
1234567891011import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void testAddition() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
Deprecated / Removed APIs to Avoid
Thread.stop(),Thread.suspend(),Thread.resume()— unsafe, deprecated for removalfinalize()— deprecated; useCleaneror try-with-resources instead- Applets (
java.applet) — removed - Security Manager — deprecated for removal (JEP 411)
new Integer(int),new Double(double), etc. — usevalueOfor autoboxingDate,Calendar,SimpleDateFormat— preferjava.timeNashornJavaScript engine — removed in Java 15javax.*Java EE modules (JAXB, JAX-WS, CORBA) — removed; use Jakarta EE artifactssun.misc.Unsafe— strongly discouraged; targeted for removal
Resources for Further Learning
- Official Java Documentation (docs.oracle.com)
- "Effective Java" (3rd ed.) by Joshua Bloch
- "Java Concurrency in Practice" by Brian Goetz et al.
- Oracle Java Tutorials and JEP index (openjdk.org/jeps)
- Spring.io Documentation
- Baeldung, Inside Java, and Java Magazine
- Stack Overflow Java community
- GitHub open-source Java projects
Advanced Concepts
- Virtual threads and structured concurrency (
StructuredTaskScope) - Pattern matching and record patterns
- Sealed types and exhaustive switches
- Java Memory Model and
VarHandle - Foreign Function & Memory API (
java.lang.foreign, standard since Java 22) - Reflection and the Java Module System (JPMS)
- Annotations and annotation processing
- GraalVM and native image compilation
- Performance tuning (G1, ZGC, Shenandoah, JFR, JMH)
Continue Learning
Discover more cheatsheets to boost your productivity