if, else if, else조건에 따라 코드 블록을 선택적으로 실행한다.
public class Main {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 80) {
System.out.println("B");
} else {
System.out.println("Under C");
}
}
}
// B
switch여러 값 중 하나와 일치하는 분기를 선택하여 실행한다.
public class Main {
public static void main(String[] args) {
int menu = 2;
switch (menu) {
case 1:
System.out.println("주식 조회");
break;
case 2:
System.out.println("주식 매수");
break;
case 3:
System.out.println("주식 매도");a
break;
default:
System.out.println("유효하지 않은 선택지");
}
}
}
// 주식 매수
for조건에 따라 정해진 횟수만큼 반복한다.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("주식 가격 확인: " + i + "일차");
}
}
}
/*
* 주식 가격 확인: 1일차
* 주식 가격 확인: 2일차
* 주식 가격 확인: 3일차
* 주식 가격 확인: 4일차
* 주식 가격 확인: 5일차
*/
for-each배열이나 컬렉션의 모든 요소를 순서대로 반복할 때 사용한다. 인덱스가 없고 순차 접근만 가능하다. 루프 변수에 새 값을 대입해도 원본 배열이나 컬렉션의 요소 참조가 바뀌지 않는다.
public class Main {
public static void main(String[] args) {
String[] stocks = {"Stock1", "Stock2", "Stock3"};
for (String stock : stocks) {
System.out.println("보유 주식: " + stock);
}
}
}
/*
* 보유 주식: Stock1
* 보유 주식: Stock2
* 보유 주식: Stock3
*/
while조건이 참인 동안 계속 반복한다.
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
System.out.println("잔고 확인: " + i + "번째");
i++;
}
}
}
/*
* 잔고 확인: 1번째
* 잔고 확인: 2번째
* 잔고 확인: 3번째
*/
do-while최소 1회는 실행되고 조건이 참인 동안 반복한다.
public class Main {
public static void main(String[] args) {
int count = 0;
do {
System.out.println("거래 내역 조회 시도: " + count);
count++;
} while (count < 2);
}
}
/*
* 거래 내역 조회 시도: 0
* 거래 내역 조회 시도: 1
*/
✏️ Stream API?
컬렉션이나 배열을 선언형 (무엇을 할 것인가) 방식으로 처리할 때 사용하는 라이브러리다. 반복문 대신 함수형 스타일로 데이터를 필터링, 매핑, 정렬, 집계할 수 있어 간결한 코드 작성이 가능하다.주요 메서드
메서드 유형 설명 stream()생성 컬렉션으로부터 Stream 생성 filter()중간 조건에 맞는 요소만 통과 map()중간 각 요소를 다른 값으로 변환 sorted()중간 정렬 distinct()중간 중복 제거 limit(),skip()중간 일부 요소 제한 또는 건너뜀 collect()최종 결과 수집 (List, Set, Map 등) forEach()최종 각 요소에 대해 작업 수행 count()최종 요소 개수 반환 anyMatch()/allMatch()/noneMatch()최종 조건 일치 여부 확인 import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> stocks = Arrays.asList("Apple", "Amazon", "Google", "Microsoft"); stocks.stream().filter(s -> s.startsWith("A")).forEach(System.out::println); List<Integer> prices = Arrays.asList(1000, 2000, 3000); double avg = prices.stream().mapToInt(Integer::intValue).average().orElse(0); System.out.println("Average Price: " + avg); } } /* * Apple * Amazon * Average Price: 2000.0 */
break현재 반복문 또는 switch문을 즉시 종료한다.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
System.out.println("거래 횟수: " + i);
}
}
}
/*
* 거래 횟수: 1
* 거래 횟수: 2
* 거래 횟수: 3
*/
continue현재 반복을 건너뛰고 다음 반복으로 진행한다.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("처리 중인 거래 번호: " + i);
}
}
}
/*
* 처리 중인 거래 번호: 1
* 처리 중인 거래 번호: 2
* 처리 중인 거래 번호: 4
* 처리 중인 거래 번호: 5
*/
return현재 메서드의 실행을 종료하고 값을 반환하거나 단순히 종료한다.
public class Main {
public static int getBalance() {
return 100000; // 100000 반환
}
}
try-catch-finally예외 발생 시 프로그램이 중단되지 않도록 예외 상황을 처리하기 위한 제어 흐름 구조다.
public class Main {
public static void main(String[] args) {
try {
int[] stocks = { 10, 20 };
System.out.println(stocks[2]); // 예외 발생
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index Error: " + e.getMessage());
} finally {
System.out.println("Exception handling completed.");
}
}
}
/*
* Index Error: Index 2 out of bounds for length 2
* Exception handling completed.
*/
throw, throws예외를 발생시키거나 메서드에서 예외가 발생할 수 있음을 명시한다.
public class Main {
public static void buyStock(int amount) throws Exception {
if (amount <= 0) {
throw new Exception("Amount must be bigger than zero.");
}
System.out.println("Bought " + amount + " stocks successfully.");
}
public static void main(String[] args) {
try {
buyStock(10);
buyStock(0);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
/*
* Bought 10 stocks successfully.
* Exception: Amount must be bigger than zero.
*/