if 만으로는 좀 더 복잡한 내용을 처리하는데 부족하다.
if-else절은 if 절의 값이 true일 때 then절이 실행되고, false일 때 else절이 실행된다.
if (false) {
System.out.println(1);
} else {
System.out.println(2);
}
}
}
< if(true) : then절 실행 → 1 >
package org.opentutorials.javatutorials.condition;
public class Condition3Demo {
public static void main(String[] args) {
if (true) {
System.out.println(1);
} else {
System.out.println(2);
}
}
}
< if(false) : else절 실행 → 2 >
if(false){
System.out.println(1);
} else {
System.out.println(2);
}
else if :
else if절을 이용하면 조건문의 흐름을 좀 더 제어할 수 있음.
▶ if절의 값이 true라면 then절이 실행된다.
▶ if절의 값이 false라면 else if절로 제어가 넘어간다.
▶ else if절의 값이 true라면 else if then절이 실행된다.
▶ false라면 else절이 실행.
∴ else if 절은 여러개가 복수로 등장할 수 있고 else절은 생략 가능.
∴ else절이 else if절보다 먼저 등장 할 수는 없음.
1. < if절의 값이 false라면 else if절로 제어가 넘어간다. → 2 >
package org.opentutorials.javatutorials.condition;
public class ElseDemo {
public static void main(String[] args) {
if (false) {
System.out.println(1);
} else if (true) {
System.out.println(2);
} else if (true) {
System.out.println(3);
} else {
System.out.println(4);
}
}
}
2. < else if절의 값이 true라면 else if then절이 실행됨 → 3>
if(false){
System.out.println(1);
} else if(false) {
System.out.println(2);
} else if(true) {
System.out.println(3);
} else {
System.out.println(4);
}
<false라면 else절이 실행됨 → 4>
if(false){
System.out.println(1);
} else if(false) {
System.out.println(2);
} else if(false) {
System.out.println(3);
} else {
System.out.println(4);
}
'PL(ProgrammingLanguage) > JAVA' 카테고리의 다른 글
조건문(중첩) (0) | 2021.02.28 |
---|---|
조건문(응용) (0) | 2021.02.28 |
조건문 (if) (0) | 2021.02.28 |
Boolean과 Comparison Operator (0) | 2021.02.28 |
연산자(단항연산자) (0) | 2021.02.28 |