Day 6: Java의 if, else if, else 문 이해하기
발행: (2025년 12월 25일 오전 02:43 GMT+9)
3 min read
원문: Dev.to
Source: Dev.to
조건문이란?
Java의 조건문은 조건이 참일 때만 프로그램 흐름을 제어하는 데 사용됩니다. 이는 프로그램이 입력에 따라 다르게 동작해야 할 때 매우 유용합니다.
if 문
if 문은 괄호 안의 조건을 검사합니다.
- 조건이 참이면 블록 안의 코드가 실행됩니다.
- 조건이 거짓이면 코드는 건너뛰어집니다.
예시
int score = 60;
if (score >= 50) {
System.out.println("You passed the exam!");
}
else if 문
첫 번째 if 조건이 거짓일 때 다른 조건을 검사하기 위해 else if 문을 사용합니다.
예시
int score = 75;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 50) {
System.out.println("You passed.");
}
else 문
위의 어떤 조건도 참이 아닐 때 실행되는 블록이 else 문입니다.
예시
int score = 40;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 50) {
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
기억해야 할 간단한 규칙
if→ 첫 번째 조건을 검사else if→ 추가 조건을 검사else→ 모든 조건이 거짓일 때 실행
if–else if–else 구조에서는 하나의 블록만 실행됩니다.
오늘의 과제
계좌 잔액을 5000으로 설정합니다.
- 잔액이 5000 이하이면:
"Withdrawal successfully"출력 - 잔액이 5000 초과이면:
"Withdrawal Failed"출력
샘플 코드
package demo;
public class Sample {
public static void main(String[] args) {
int balance = 4500;
if (balance > 5000) {
System.out.println("Withdrawal Failed!");
} else {
System.out.println("Withdrawal successfull");
}
}
}
설명
balance는 현재4500으로 설정되어 있습니다.- 잔액이
5000보다 작으므로 프로그램은 **“Withdrawal successfull”**을 출력합니다. - 만약 잔액이
5000보다 크다면 **“Withdrawal Failed!”**가 출력될 것입니다.