✔ 1) List / Set / Map 심화
✔ 2) 메서드 만들기 연습
✔ 3) 예외 처리(try/catch)
✔ 4) Stream
📌 메서드 기본 형태
public *리턴타입* 메서드명(파라미터...) {
실행할 코드
return 값;
}
[예시1] 두 수 더하는 메서드
public int add(int a, int b) {
return a + b;
}
// 사용
int result = add(10, 20);
System.out.println(result); // 30
[예시2] 문자열을 3번 반복하는 메서드
public String repeat3(String word) {
return word + word + word;
}
System.out.println(repeat3("hi")); // hihihi
public int getMax(int a, int b) {
return (a > b) ? a : b;
}
예외(에러)란?
📌 기본 try / catch 구조
try {
위험한 코드
} catch (Exception e) {
예외 발생 시 실행할 코드
}
[예시1] 0으로 나누기 방지
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다.");
}
[예시2] 배열 인덱스 예외
int[] arr = {1, 2, 3};
try {
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("잘못된 인덱스입니다.");
}
문자열 "abc" 를 Integer.parseInt() 로 숫자로 바꾸면 예외가 발생한다.
try/catch로 예외를 처리하여 숫자로 변환할 수 없습니다. 를 출력하는 코드를 작성하라.
try {
int a = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("숫자로 변환할 수 없습니다.");
}
or
try {
int a = Integer.parseInt("abc");
} catch (Exception e) {
System.out.println("숫자로 변환할 수 없습니다.");
}
Stream은 컬렉션 반복을 더 간단하게 쓰는 문법이라고 보면 됨.
[예시1] 리스트의 모든 값 출력
List<Integer> list = List.of(1, 2, 3, 4);
list.stream()
.forEach(num -> System.out.println(num));
✔ 필터(filter) 사용
[예시2] 짝수만 출력
list.stream()
.filter(num -> num % 2 == 0)
.forEach(num -> System.out.println(num));
✔ map 사용
[예시3] 문자열을 모두 대문자로
List<String> words = List.of("java", "spring", "backend");
words.stream()
.map(word -> word.toUpperCase())
.forEach(System.out::println);
✔ reduce 사용 (합계 구하기)
[예시4] 모두 더하기
int sum = list.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum);
❗ Q3. 다음 리스트에서 10, 13, 22, 35, 40 Stream을 사용해서 짝수만 출력하는 코드를 작성하라.
List<Integer> list = List.of(10, 13, 22, 35, 40);
list.stream()
.filter(num -> num % 2 == 0)
.forEach(num -> System.out.println(num));