📖 Guide
Java — Complete Reference
Comprehensive Java cheat sheet covering data types, strings, collections, OOP, interfaces, exceptions, file I/O, streams, lambdas, and more.
203 commands across 12 categories
BasicsData TypesStringsArrays & CollectionsControl FlowMethodsClasses & OOPInterfaces & AbstractException HandlingFile I/OStreams & LambdasCommon Utilities
Basics
| Command | Description |
|---|---|
public class Main { public static void main(String[] args) { } } | Java program entry point |
System.out.println("Hello"); | Print line to standard output |
System.out.print("no newline"); | Print without trailing newline |
System.out.printf("Name: %s, Age: %d%n", name, age); | Formatted print (like C printf) |
// single line comment | Single-line comment |
/* multi-line comment */ | Multi-line comment |
/** Javadoc comment */ | Documentation comment |
final int MAX = 100; | Declare a constant (cannot be reassigned) |
var name = "Java"; | Local variable type inference (Java 10+) |
Scanner sc = new Scanner(System.in);e.g. String line = sc.nextLine(); int n = sc.nextInt(); | Read user input from console |
import java.util.*; | Import all classes from a package |
package com.example.app; | Declare the package for the class |
Data Types
| Command | Description |
|---|---|
byte b = 127; | 8-bit signed integer (-128 to 127) |
short s = 32000; | 16-bit signed integer |
int i = 42; | 32-bit signed integer |
long l = 100_000L; | 64-bit signed integer (suffix L) |
float f = 3.14f; | 32-bit floating point (suffix f) |
double d = 3.14159; | 64-bit floating point (default for decimals) |
boolean flag = true; | Boolean (true or false) |
char c = 'A'; | 16-bit Unicode character |
Integer.parseInt("42") | Parse string to int |
Double.parseDouble("3.14") | Parse string to double |
String.valueOf(42) | Convert any type to String |
(int) 3.7e.g. int x = (int) 3.7; // 3 | Type casting (truncates to 3) |
Integer x = 5; | Autoboxing — primitive to wrapper object |
int y = x; | Unboxing — wrapper object to primitive |
enum Color { RED, GREEN, BLUE } | Define an enum type |
Strings
| Command | Description |
|---|---|
String s = "Hello"; | String literal (immutable) |
s.length() | Get string length |
s.charAt(0) | Get character at index |
s.substring(1, 4) | Extract substring (start inclusive, end exclusive) |
s.indexOf("lo") | Find first index of substring (-1 if not found) |
s.lastIndexOf("l") | Find last index of character/substring |
s.contains("ell") | Check if string contains substring |
s.startsWith("He") | Check if string starts with prefix |
s.endsWith("lo") | Check if string ends with suffix |
s.equals("Hello") | Compare strings for equality (not ==) |
s.equalsIgnoreCase("hello") | Case-insensitive comparison |
s.compareTo("other") | Lexicographic comparison (returns int) |
s.toUpperCase() | Convert to uppercase |
s.toLowerCase() | Convert to lowercase |
s.trim() | Remove leading/trailing whitespace |
s.strip() | Remove whitespace (Unicode-aware, Java 11+) |
s.replace("old", "new") | Replace all occurrences of literal |
s.replaceAll("regex", "new") | Replace all regex matches |
s.split(",")e.g. String[] parts = "a,b,c".split(","); | Split into String array |
String.join(", ", list) | Join strings with delimiter |
s.isEmpty() | Check if string is empty (length == 0) |
s.isBlank() | Check if string is blank (empty or whitespace, Java 11+) |
s.formatted("arg")e.g. "Hello %s".formatted("World") | Format string (Java 15+) |
new StringBuilder()e.g. sb.append("a").append("b").toString() | Mutable string builder for concatenation |
"""\ntext block\n""" | Text block / multi-line string (Java 15+) |
Arrays & Collections
| Command | Description |
|---|---|
int[] arr = new int[5]; | Declare array with fixed size |
int[] arr = {1, 2, 3, 4, 5}; | Declare and initialize array |
arr.length | Get array length (field, not method) |
Arrays.sort(arr) | Sort array in place |
Arrays.copyOf(arr, newLen) | Copy array with new length |
Arrays.fill(arr, value) | Fill array with a value |
Arrays.asList(arr) | Convert array to fixed-size List |
List<String> list = new ArrayList<>(); | Create a dynamic list |
List.of("a", "b", "c") | Create immutable list (Java 9+) |
list.add(item) | Add element to list |
list.get(index) | Get element at index |
list.set(index, value) | Replace element at index |
list.remove(index) | Remove element at index |
list.size() | Get number of elements |
list.contains(item) | Check if list contains element |
list.indexOf(item) | Find index of element |
Collections.sort(list) | Sort a list |
Collections.unmodifiableList(list) | Create unmodifiable view of list |
Map<String, Integer> map = new HashMap<>(); | Create a hash map |
Map.of("a", 1, "b", 2) | Create immutable map (Java 9+) |
map.put(key, value) | Insert/update key-value pair |
map.get(key) | Get value by key (null if absent) |
map.getOrDefault(key, defaultVal) | Get value or default |
map.containsKey(key) | Check if key exists |
map.keySet() / map.values() / map.entrySet() | Get keys, values, or entries |
Set<String> set = new HashSet<>(); | Create a hash set (unique elements) |
Set.of("a", "b", "c") | Create immutable set (Java 9+) |
Queue<Integer> q = new LinkedList<>(); | Create a queue (FIFO) |
Deque<Integer> stack = new ArrayDeque<>(); | Create a stack (LIFO) / double-ended queue |
Control Flow
| Command | Description |
|---|---|
if (cond) { } else if (cond) { } else { } | If-else conditional |
switch (val) { case x: break; default: } | Switch statement (classic) |
switch (val) { case x -> expr; }e.g. String s = switch(day) { case MON -> "Monday"; default -> "Other"; }; | Switch expression (Java 14+) |
for (int i = 0; i < n; i++) { } | Classic for loop |
for (Type item : collection) { } | Enhanced for-each loop |
while (cond) { } | While loop |
do { } while (cond); | Do-while loop |
break; | Exit loop or switch |
continue; | Skip to next iteration |
break label; | Break out of labeled outer loop |
condition ? valTrue : valFalse | Ternary operator |
if (obj instanceof String s) { } | Pattern matching instanceof (Java 16+) |
Methods
| Command | Description |
|---|---|
public int add(int a, int b) { return a + b; } | Method with return type and parameters |
public void doSomething() { } | Void method (no return value) |
public static int helper() { } | Static method (called on class, not instance) |
public int add(int a, int... nums) | Varargs — variable number of arguments |
method overloadinge.g. int add(int a, int b) / double add(double a, double b) | Same method name, different parameters |
@Override | Annotation — method overrides parent method |
public final void locked() { } | Final method — cannot be overridden |
private | Accessible only within the class |
protected | Accessible within package and subclasses |
public | Accessible from anywhere |
default (no modifier) | Package-private — accessible within the package |
return value; | Return a value from a method |
Classes & OOP
| Command | Description |
|---|---|
class Dog { String name; Dog(String name) { this.name = name; } } | Class with constructor |
Dog d = new Dog("Rex"); | Create object instance |
this | Reference to current object |
this(args) | Call another constructor in same class |
class Puppy extends Dog { } | Inheritance (extends one class) |
super(args) | Call parent class constructor |
super.method() | Call parent class method |
@Override public String toString() { } | Override toString for custom representation |
@Override public boolean equals(Object o) { } | Override equals for value comparison |
@Override public int hashCode() { } | Override hashCode (required with equals) |
static int count; | Static field — shared across all instances |
record Point(int x, int y) { } | Record class — immutable data carrier (Java 16+) |
sealed class Shape permits Circle, Square { } | Sealed class — restrict subclasses (Java 17+) |
obj.getClass() | Get runtime class of object |
obj instanceof Type | Check if object is instance of type |
Interfaces & Abstract
| Command | Description |
|---|---|
interface Drawable { void draw(); } | Declare an interface |
class Circle implements Drawable { public void draw() { } } | Implement an interface |
interface A extends B, C { } | Interface extending multiple interfaces |
default void method() { } | Default method in interface (Java 8+) |
static void helper() { } | Static method in interface |
private void internal() { } | Private method in interface (Java 9+) |
abstract class Shape { abstract double area(); } | Abstract class with abstract method |
class Circle extends Shape { double area() { return Math.PI * r * r; } } | Extend abstract class and implement methods |
@FunctionalInterface | Interface with exactly one abstract method (for lambdas) |
Comparable<T>e.g. class Foo implements Comparable<Foo> { public int compareTo(Foo o) { } } | Interface for natural ordering |
Comparator.comparing(Foo::getName) | Create comparator from method reference |
Exception Handling
| Command | Description |
|---|---|
try { } catch (Exception e) { } finally { } | Try-catch-finally block |
catch (IOException | SQLException e) { } | Multi-catch — handle multiple exception types |
throw new RuntimeException("message"); | Throw an unchecked exception |
throw new IOException("message"); | Throw a checked exception |
public void read() throws IOException { } | Declare checked exception in method signature |
try (var r = new FileReader("f")) { } | Try-with-resources (auto-closes) |
e.getMessage() | Get the error message |
e.printStackTrace() | Print the stack trace |
e.getCause() | Get the cause of the exception |
class MyException extends Exception { } | Custom checked exception |
class MyRuntimeException extends RuntimeException { } | Custom unchecked exception |
assert condition : "message"; | Assert a condition (enable with -ea flag) |
File I/O
| Command | Description |
|---|---|
Path path = Path.of("file.txt"); | Create a Path (Java NIO) |
Files.readString(path) | Read entire file as String (Java 11+) |
Files.readAllLines(path) | Read all lines into List<String> |
Files.writeString(path, content) | Write string to file (Java 11+) |
Files.write(path, lines) | Write list of lines to file |
Files.exists(path) | Check if file/directory exists |
Files.createDirectory(path) | Create a directory |
Files.createDirectories(path) | Create directories including parents |
Files.delete(path) | Delete a file or empty directory |
Files.copy(src, dest) | Copy a file |
Files.move(src, dest) | Move/rename a file |
Files.list(dir) | List directory contents as Stream<Path> |
Files.walk(dir) | Recursively walk directory tree as Stream<Path> |
try (var br = new BufferedReader(new FileReader("f"))) { } | Buffered file reading (classic) |
Streams & Lambdas
| Command | Description |
|---|---|
(a, b) -> a + b | Lambda expression |
list.forEach(item -> System.out.println(item)) | ForEach with lambda |
list.forEach(System.out::println) | Method reference (equivalent to above) |
list.stream() | Create a stream from collection |
Stream.of(1, 2, 3) | Create stream from values |
.filter(x -> x > 5) | Keep elements matching predicate |
.map(x -> x * 2) | Transform each element |
.flatMap(list -> list.stream()) | Flatten nested streams |
.sorted() | Sort elements (natural order) |
.sorted(Comparator.reverseOrder()) | Sort in reverse order |
.distinct() | Remove duplicates |
.limit(10) | Take first n elements |
.skip(5) | Skip first n elements |
.peek(x -> log(x)) | Perform action on each element without consuming |
.collect(Collectors.toList()) | Collect stream into a List |
.collect(Collectors.toSet()) | Collect into a Set |
.collect(Collectors.toMap(k, v)) | Collect into a Map |
.collect(Collectors.joining(", ")) | Join elements into a String |
.collect(Collectors.groupingBy(fn)) | Group elements by classifier |
.reduce(0, Integer::sum) | Reduce to single value |
.count() | Count elements in stream |
.findFirst() | Get first element as Optional |
.anyMatch(x -> x > 0) | True if any element matches |
.allMatch(x -> x > 0) | True if all elements match |
Optional<T> opt = Optional.of(val) | Create Optional with value |
opt.orElse(defaultVal) | Get value or default |
opt.ifPresent(val -> use(val)) | Execute if value present |
opt.map(fn).orElse(default) | Transform optional value |
Common Utilities
| Command | Description |
|---|---|
Math.max(a, b) / Math.min(a, b) | Maximum / minimum of two values |
Math.abs(x) | Absolute value |
Math.sqrt(x) | Square root |
Math.pow(base, exp) | Power / exponentiation |
Math.round(x) | Round to nearest integer |
Math.floor(x) / Math.ceil(x) | Floor / ceiling |
Math.random() | Random double between 0.0 and 1.0 |
new Random().nextInt(bound) | Random int from 0 to bound-1 |
LocalDate.now() | Current date |
LocalTime.now() | Current time |
LocalDateTime.now() | Current date and time |
Instant.now() | Current timestamp (UTC) |
Duration.between(start, end) | Calculate duration between two times |
DateTimeFormatter.ofPattern("yyyy-MM-dd") | Date/time formatting pattern |
Thread.sleep(1000) | Pause execution for milliseconds |
System.currentTimeMillis() | Current time in milliseconds since epoch |
Objects.equals(a, b) | Null-safe equality check |
Objects.requireNonNull(obj, "msg") | Throw NPE if null |
📖 Free, searchable command reference. Bookmark this page for quick access.