검색과 인쇄가 가능한 자바 참고자료입니다: 타입, 문자열, 컬렉션, 스트림, record, 패턴 매칭, 동시성, 파일 입출력까지. 무료입니다.

Basics & types

10
var list = new ArrayList<String>();
Local variable type inference
int x = 42; double d = 3.14;
Primitive declarations
long big = 9_000_000_000L;
Digit separators + long literal
char c = 'A'; boolean ok = true;
Char and boolean primitives
final int MAX = 100;
Constant (cannot be reassigned)
int i = (int) 3.99;
Explicit narrowing cast (→ 3)
double d = x;
Implicit widening conversion
int n = Integer.parseInt("42");
String → int
String s = String.valueOf(42);
Number → string
Integer boxed = 42; int y = boxed;
Auto-boxing and unboxing

Strings & text blocks

12
s.length(); s.charAt(0);
Length and character access
s.substring(1, 3)
Slice (end index exclusive)
s.contains("x"); s.startsWith("a");
Search checks
s.replace("a", "b")
Replace all occurrences
s.strip()
Trim whitespace (Unicode-aware)
s.split(",")
Split into a String[]
String.join(", ", parts)
Join with a separator
"ab".repeat(3)
Repeat a string ("ababab")
s.isBlank(); s.isEmpty();
Whitespace-only / zero-length
"%s: %d".formatted(key, count)
Inline printf-style formatting
String html = """\n <p>Hi</p>\n """;
Multi-line text block
new StringBuilder().append(a).append(b)
Efficient string building in loops

Collections

12
List<String> l = List.of("a", "b");
Immutable list factory
Map<String, Integer> m = Map.of("a", 1);
Immutable map factory
Set<Integer> s = Set.of(1, 2, 3);
Immutable set factory
new ArrayList<>(List.of("a", "b"))
Mutable copy of a list
List.copyOf(list)
Immutable defensive copy
map.getOrDefault(key, 0)
Read with a fallback value
map.computeIfAbsent(k, x -> new ArrayList<>())
Lazily create grouped values
map.merge(key, 1, Integer::sum)
Increment a counter map
list.removeIf(s -> s.isBlank())
Bulk remove matching items
list.sort(Comparator.naturalOrder())
Sort a list in place
for (var e : map.entrySet())
Iterate map entries
list.forEach(System.out::println)
Iterate with a method reference

Streams & lambdas

12
list.stream().map(String::toUpperCase).toList()
Transform every element
.filter(n -> n > 0)
Keep matching elements
.sorted(Comparator.comparing(User::name))
Sort by a key extractor
.distinct().limit(10).skip(5)
Dedupe and paginate a stream
.collect(Collectors.groupingBy(User::city))
Group into Map<K, List<V>>
.collect(Collectors.joining(", "))
Join strings with a separator
.collect(Collectors.toMap(User::id, u -> u))
Build a map from a stream
.flatMap(List::stream)
Flatten nested collections
.mapToInt(Order::total).sum()
Numeric stream aggregation
.reduce(0, Integer::sum)
Fold to a single value
.anyMatch(s -> s.isBlank())
anyMatch / allMatch / noneMatch
IntStream.range(0, 10)
Stream of ints 0..9

Records & sealed classes

9
record Point(int x, int y) {}
Immutable data carrier
var p = new Point(1, 2); p.x();
Construct + generated accessors
equals(), hashCode(), toString()
Generated for free on records
record Range(int lo, int hi) { Range { if (lo > hi) throw new IllegalArgumentException(); } }
Compact constructor validation
record Point(...) implements Shape {}
Records can implement interfaces
static Point origin() { return new Point(0, 0); }
Static factory inside a record
sealed interface Shape permits Circle, Square {}
Restrict allowed subtypes
final class Circle implements Shape {}
Permitted type must be final...
non-sealed class Square implements Shape {}
...or sealed / non-sealed

Pattern matching & switch

8
if (obj instanceof String s) use(s);
instanceof pattern binds a var
int n = switch (day) { case MON -> 1; default -> 0; };
Switch as an expression
case MON, TUE -> "early week";
Multiple labels per arm
case X -> { ...; yield value; }
Block arm returns via yield
case String s when s.length() > 2 ->
Guarded pattern (when clause)
case Point(int x, int y) -> x + y;
Record pattern deconstruction
case null, default -> "none";
Handle null inside the switch
switch (shape) { case Circle c -> ... }
Exhaustive over sealed types

OOP essentials

11
interface Greeter { default String hi() { return "hi"; } }
Interface with default method
class Impl implements A, B {}
Implement multiple interfaces
class Admin extends User {}
Single-class inheritance
@Override public String toString()
Mark overridden methods
super.method(); super(args);
Call parent method / constructor
class Box<T> { T value; }
Generic class
<T extends Comparable<T>> T max(...)
Bounded type parameter
List<? extends Number> nums
Covariant wildcard
enum Status { ACTIVE, DONE }
Enum type (can hold methods)
abstract class Base { abstract void run(); }
Abstract class + method
public static User of(String n) { ... }
Static factory method idiom

Optional

10
Optional.of(v); Optional.empty();
Create (of throws on null)
Optional.ofNullable(maybeNull)
Wrap a possibly-null value
opt.isPresent(); opt.isEmpty();
Presence checks
opt.orElse(defaultValue)
Fallback value
opt.orElseGet(() -> compute())
Lazy fallback (only if empty)
opt.orElseThrow()
Get or throw NoSuchElement
opt.map(User::name).filter(n -> !n.isBlank())
Chain transformations safely
opt.ifPresent(v -> use(v))
Run only when present
opt.ifPresentOrElse(use, this::warn)
Branch on both cases
opt.get()
Avoid: prefer orElseThrow()

Exceptions & try-with-resources

9
try { ... } catch (IOException e) { ... }
Catch a checked exception
catch (IOException | SQLException e)
Multi-catch in one block
finally { cleanup(); }
Always runs (even on throw)
try (var in = Files.newBufferedReader(p)) { ... }
Auto-close resources
throw new IllegalArgumentException("bad id");
Throw with a message
class AppException extends RuntimeException {}
Custom unchecked exception
RuntimeException vs Exception
Unchecked vs checked (declared)
e.getMessage(); e.getCause();
Inspect an exception
Objects.requireNonNull(x, "x is required")
Fail fast on null arguments

Concurrency

12
Thread.startVirtualThread(() -> work());
Cheap virtual thread (21+)
Executors.newVirtualThreadPerTaskExecutor()
One virtual thread per task
var pool = Executors.newFixedThreadPool(4);
Bounded platform thread pool
Future<T> f = pool.submit(task); f.get();
Submit and await a result
CompletableFuture.supplyAsync(() -> fetch())
Async computation
.thenApply(r -> parse(r))
Transform the async result
.thenCombine(other, (a, b) -> a + b)
Join two futures
.exceptionally(e -> fallback)
Recover from async failure
CompletableFuture.allOf(f1, f2).join();
Wait for all to finish
new AtomicInteger().incrementAndGet()
Lock-free counter
new ConcurrentHashMap<K, V>()
Thread-safe map
synchronized (lock) { ... }
Mutual exclusion block

I/O & files (java.nio)

12
Path p = Path.of("data", "file.txt");
Build a platform-safe path
String s = Files.readString(p);
Read a whole file as text
Files.writeString(p, text);
Write text (creates/truncates)
List<String> lines = Files.readAllLines(p);
Read all lines
try (var st = Files.lines(p)) { ... }
Stream lines lazily
Files.exists(p); Files.size(p);
Existence and size checks
Files.createDirectories(dir);
mkdir -p equivalent
Files.copy(src, dst); Files.move(src, dst);
Copy / move files
Files.deleteIfExists(p);
Delete without throwing
try (var files = Files.list(dir)) { ... }
List directory entries
Files.walk(dir)
Recursive directory stream
Files.createTempFile("up-", ".tmp")
Temporary file

Build & CLI

12
javac Main.java && java Main
Compile then run
java Main.java
Run a source file directly
java -jar app.jar
Run an executable jar
java -Xmx512m -jar app.jar
Cap the max heap size
jshell
Interactive Java REPL
mvn clean package
Maven: build the artifact
mvn test
Maven: run the test suite
mvn dependency:tree
Maven: inspect dependencies
./gradlew build
Gradle: full build via wrapper
./gradlew test --tests "UserTest"
Gradle: run selected tests
jar tf app.jar
List a jar's contents
java --version
Show the JDK version

“:q”와 일치하는 항목이 없습니다.


자바 치트시트 소개

이 자바 치트시트는 최신 자바를 검색 가능한 한 페이지로 압축했습니다: 기초와 타입, 문자열과 텍스트 블록, 컬렉션, 스트림과 람다, record와 sealed 클래스, 패턴 매칭과 switch, OOP 핵심, Optional, 예외와 try-with-resources, 동시성, java.nio를 이용한 파일 입출력, 그리고 빌드와 CLI 명령어까지 다룹니다.

매일 작성하는 기초 문법(List, HashMap, for-each 루프, try-with-resources 블록)과 자바가 읽히는 방식을 바꾼 최신 언어 기능(record, sealed 타입, 패턴 매칭을 사용한 switch 표현식, 텍스트 블록)을 모두 다룹니다.

이 시트는 무료이며 클라이언트 측에서 동작합니다: 검색창으로 실시간으로 행을 필터링하고, 고정된 목차로 섹션을 이동하고, 클릭 한 번으로 스니펫을 복사하고, 키보드 옆에 두고 볼 수 있도록 페이지를 인쇄할 수 있습니다.

자바 치트시트 사용 방법

  1. 기초와 타입, 컬렉션부터 동시성, 빌드 & CLI까지 섹션을 훑어보세요.
  2. stream, record, Optional 같은 키워드를 검색해 모든 행을 실시간으로 필터링하세요.
  3. 최신 문법이 필요할 때는 패턴 매칭 & switch 또는 스트림 & 람다 섹션으로 이동하세요.
  4. 스니펫이나 복사 아이콘을 클릭해 자바 코드를 클립보드에 복사하세요.
  5. 오프라인 자바 참고자료로 시트를 인쇄하세요.

자주 묻는 질문

12개 섹션입니다: 기초와 타입, 문자열과 텍스트 블록, 컬렉션, 스트림과 람다, record와 sealed 클래스, 패턴 매칭과 switch, OOP 핵심, Optional, 예외와 try-with-resources, 동시성, java.nio 파일 입출력, 빌드와 CLI 명령어입니다.

네. record, sealed 클래스, 텍스트 블록, var, 강화된 switch 표현식, 패턴 매칭이 클래식 문법과 함께 각각 별도의 행으로 다뤄집니다.

실제로 자주 작성하는 내용을 중심으로 구성되어 있습니다: List, Set, Map, Deque의 생성과 순회, 그리고 map, filter, collect, groupingBy, reduce와 자주 쓰는 컬렉터입니다.

네. 어떤 스니펫이든 클릭하거나 마우스오버 시 나타나는 복사 아이콘을 클릭하면 짧은 확인 메시지와 함께 클립보드에 저장됩니다.

네, 완전히 무료입니다: 검색과 인쇄가 가능하며 가입 없이 브라우저에서 렌더링됩니다.


인기 검색어
자바 치트시트 자바 문법 참고자료 자바 컬렉션 치트시트 자바 스트림 예제 자바 record와 sealed 클래스 자바 switch 패턴 매칭 자바 동시성 기초
도움이 필요하신가요?
이 도구에서 문제를 발견하셨나요? 저희 팀에 알려주세요.
문제 신고

이 무료 도구를 귀하의 웹사이트에 추가하세요: 아래 코드를 복사하여 붙여넣으세요.