Cheatsheet - Java
Compilation & Execution
# Compile and run
$ javac Main.java && java Main
# Single-file source code execution (Java 11+)
$ java Main.java
# Run packaged executable JAR
$ java -jar app.jar
# JVM options
$ java -Xms512m -Xmx4g -XX:+UseG1GC -jar app.jar
Primitive Types & Numbers
// Primitives: byte (8-bit), short (16-bit), int (32-bit), long (64-bit)
long largeNum = 1_000_000_000L;
float f = 3.14f;
double d = 3.1415926535;
boolean flag = true;
char ch = 'A'; // 16-bit Unicode
// Binary & Hex literals
int bin = 0b1010; // 10
int hex = 0x7F; // 127
// Bitwise Operations
int shifted = 1 << 4; // 16 (left shift)
int unsignedShift = -1 >>> 1; // 2147483647 (zero-fill right shift)
int bitAnd = 0b1100 & 0b1010; // 0b1000 (8)
int bitOr = 0b1100 | 0b1010; // 0b1110 (14)
int bitXor = 0b1100 ^ 0b1010; // 0b0110 (6)
// Parsing & Limits
int maxInt = Integer.MAX_VALUE; // 2,147,483,647
int parsed = Integer.parseInt("123"); // primitive int
Integer obj = Integer.valueOf("123"); // boxed Integer
String hexStr = Integer.toHexString(255); // "ff"
Strings & Text Blocks
String s = " Java 21 ";
s.strip(); // "Java 21" (Unicode-aware trim)
s.substring(0, 4); // "Java"
s.startsWith(" J"); // True
s.contains("21"); // True
s.replace("21", "22"); // Literal replacement
s.split("\\|"); // Regex split (escape special chars)
// Multiline Text Blocks (Java 15+)
String json = """
{
"name": "Java",
"version": 21
}
""";
// Formatting
String formatted = String.format("User: %s, Score: %.2f", "Alice", 98.765);
Collections & Streams
List, Set, and Map Creation
// Immutable Collections (Java 9+)
List<String> list = List.of("A", "B", "C");
Set<Integer> set = Set.of(1, 2, 3);
Map<String, Integer> map = Map.of("k1", 1, "k2", 2);
// Mutable Collections
List<String> mutableList = new ArrayList<>(list);
mutableList.add("D");
mutableList.removeIf(s -> s.startsWith("A"));
Map<String, Integer> mutableMap = new HashMap<>(map);
mutableMap.put("k3", 3);
mutableMap.getOrDefault("k4", 0); // 0
mutableMap.computeIfAbsent("k5", k -> k.length());
Stream Pipeline Operations
List<String> names = List.of("charlie", "alice", "bob", "alice");
// Filter, map, sort, and collect to List (Java 16+ .toList())
List<String> filtered = names.stream()
.filter(n -> n.length() > 3)
.map(String::toUpperCase)
.distinct()
.sorted()
.toList(); // ["ALICE", "CHARLIE"]
// Joining Strings
String csv = names.stream().collect(Collectors.joining(", "));
// Grouping By
Map<Integer, List<String>> byLength = names.stream()
.collect(Collectors.groupingBy(String::length));
Modern Control Flow & Pattern Matching
Switch Expressions (Java 14+)
String dayType = switch (day) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
case SATURDAY, SUNDAY -> "Weekend";
};
// Pattern Matching for switch (Java 21+)
static String formatValue(Object obj) {
return switch (obj) {
case Integer i -> String.format("int: %d", i);
case Long l -> String.format("long: %d", l);
case String s when !s.isEmpty() -> String.format("non-empty string: %s", s);
case null -> "null value";
default -> obj.toString();
};
}
Record Types (Java 16+)
Concise immutable data carrier classes with auto-generated constructor, getters, equals(), hashCode(), and toString():
public record User(long id, String name, String email) {}
User user = new User(1L, "Alice", "[email protected]");
System.out.println(user.name()); // "Alice"
Date & Time (java.time)
import java.time.*;
import java.time.format.DateTimeFormatter;
// Instant & Timestamps
Instant now = Instant.now();
LocalDate today = LocalDate.now(); // 2024-05-18
LocalTime time = LocalTime.now(); // 14:30:00
LocalDateTime dt = LocalDateTime.now(); // 2024-05-18T14:30:00
ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
// Parsing & Formatting
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String str = dt.format(fmt);
LocalDate parsed = LocalDate.parse("2024-05-18");
// Duration & Period
LocalDate nextWeek = today.plusDays(7);
Duration duration = Duration.ofMinutes(90);
Period period = Period.between(today, nextWeek);
Virtual Threads & Concurrency (Java 21+)
// Spawn a lightweight virtual thread
Thread.startVirtualThread(() -> {
System.out.println("Running on virtual thread: " + Thread.currentThread());
});
// ExecutorService with virtual threads per task
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100));
return i;
});
});
} // Automatically awaits completion of all virtual threads
Recommended ReadingSponsored
Cheatsheets - Kubernetes
Cheatsheets - Cloud
Cheatsheets - Tools
Cheatsheets - Editors
Cheatsheets - Databases
Cheatsheets - Shell
Cheatsheets - Lookups


