public class IfEx {
public static void main(String[] args) {
if(true){
System.out.println("실행 1"); // 실행
}
if(false){ // false
System.out.println("실행 2");
System.out.println("실행 3");
}
if(3!=3) // false
System.out.println("실행 4");
System.out.println("실행 5"); // 실행
}
} if else
- 조건식이 true일 경우 if블록 실행문이 실행되고, false일 경우 else블록의 실행문이 실행
public class IfElseEx02 {
public static void main(String[] args) {
int a = 10, b = 20, c = 9;
int max;
if (a > b && a > c) {
max = a; // 위의 조건식이 true일때 실행
} else { // 위의 조건식이 false일때 실행
if (b > c) {
max = b; // 위의 조건식 true일때 실행
} else {
max = c; // 위의 조건식 false일때 실행
}
}
System.out.println("max = " + max);
}
}
if / else if / else 문
- 처음 if문 조건식의 조건문이 true일 경우 처음 if문 블록이 실행되고, false일 경우 다음 조건식의 결과에 따라 실행
- else if문의 수는 제한이 없지만, 많은 else if문은 실행 속도를 느리게 함
- 마지막 else 블록은 생략 가능
public class ElseIfEx {
public static void main(String[] args) {
int age = 22;
if(age>=20 && age<30){ // 조건식 1
// 조건식 1이 true일 때 실행
System.out.println("20대");
}else if(age<20){ // 조건식 2
// 조건식 1이 false이면서 조건식 2가 true일 때 실행
System.out.println("10대 이하");
}else{
// 조건식 1과 2가 false일 때 실행
System.out.println("30대 이상");
}
}
}