Java
정적 타입 객체지향 언어. JVM 위에서 실행되어 플랫폼 독립적. Spring Boot 백엔드 개발에 주로 사용.
기본 타입
// Primitive
int a = 10;
long b = 10L;
double c = 3.14;
boolean d = true;
char e = 'A';
// Reference
String s = "안녕";
Integer n = 10; // 오토박싱
// var (Java 10+)
var name = "김탄";
var list = new ArrayList<String>();문자열
String s = "Hello";
s.length();
s.toUpperCase();
s.toLowerCase();
s.trim();
s.contains("ell");
s.startsWith("He");
s.replace("Hello", "Hi");
s.split(",");
s.substring(0, 3);
// 포맷
String.format("이름: %s, 나이: %d", name, age);
"이름: %s".formatted(name); // Java 15+
// StringBuilder (가변, 성능)
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" World");
sb.toString();컬렉션
import java.util.*;
// List
List<String> list = new ArrayList<>();
list.add("a");
list.get(0);
list.size();
list.remove("a");
list.contains("a");
Collections.sort(list);
// Map
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.get("a");
map.getOrDefault("b", 0);
map.containsKey("a");
map.forEach((k, v) -> System.out.println(k + ": " + v));
// Set
Set<String> set = new HashSet<>();
set.add("a");
set.contains("a");
// 불변 컬렉션 (Java 9+)
List<String> immutable = List.of("a", "b", "c");
Map<String, Integer> immutableMap = Map.of("a", 1, "b", 2);Stream API
import java.util.stream.*;
List<Integer> nums = List.of(1, 2, 3, 4, 5);
// map, filter, collect
List<Integer> result = nums.stream()
.filter(n -> n > 2)
.map(n -> n * 2)
.collect(Collectors.toList());
// 집계
int sum = nums.stream().mapToInt(Integer::intValue).sum();
Optional<Integer> max = nums.stream().max(Integer::compareTo);
// 그룹핑
Map<Boolean, List<Integer>> grouped = nums.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
// 문자열 조인
String joined = list.stream().collect(Collectors.joining(", "));클래스 & 인터페이스
public class Animal {
private final String name;
public Animal(String name) {
this.name = name;
}
public String speak() { return ""; }
public String getName() { return name; }
}
public class Dog extends Animal {
public Dog(String name) { super(name); }
@Override
public String speak() {
return getName() + ": 왈왈";
}
}
// 인터페이스
public interface Speakable {
String speak();
default String shout() { return speak().toUpperCase(); } // 기본 구현
}
// Record (Java 16+ — 불변 데이터 클래스)
public record Point(int x, int y) {}
Point p = new Point(1, 2);
p.x(); // getter 자동 생성예외 처리
// Checked Exception — 반드시 처리
try {
Files.readString(Path.of("file.txt"));
} catch (IOException e) {
System.err.println(e.getMessage());
} finally {
// 항상 실행
}
// try-with-resources (AutoCloseable 자동 닫기)
try (var reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
}
// Unchecked Exception — RuntimeException 하위
throw new IllegalArgumentException("잘못된 값: " + value);
throw new IllegalStateException("잘못된 상태");Optional
Optional<String> opt = Optional.ofNullable(getValue());
opt.isPresent();
opt.isEmpty(); // Java 11+
opt.get(); // 없으면 예외
opt.orElse("기본값");
opt.orElseGet(() -> computeDefault());
opt.orElseThrow(() -> new NotFoundException());
opt.map(String::toUpperCase);
opt.ifPresent(v -> System.out.println(v));비동기 (CompletableFuture)
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> fetchData())
.thenApply(data -> process(data))
.exceptionally(e -> "오류: " + e.getMessage());
String result = future.get(); // 블로킹 대기
// 병렬 실행
CompletableFuture.allOf(f1, f2, f3).join();유용한 문법 (최신)
// Switch Expression (Java 14+)
String label = switch (day) {
case MONDAY, TUESDAY -> "평일";
case SATURDAY, SUNDAY -> "주말";
default -> "기타";
};
// Pattern Matching instanceof (Java 16+)
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}
// Text Block (Java 15+)
String json = """
{
"name": "김탄"
}
""";
// Sealed Class (Java 17+)
public sealed class Shape permits Circle, Rectangle {}