It is a process that is performed only in a specific situation. If it's OO, it's like XX. For example, if the weather forecast is rainy, bring an umbrella. For if statement
Main.java
if (Conditional expression) {
processing;
}
Applying to the previous example
Main.java
if (weather forecast==rain) {
Bring an umbrella;
}
It will be. Apply an if statement to a number. If true
Main.java
int x = 10;
if (x == 10){
System.out.println("x is 10");
}
In the above case, the conditional branch of (x == 10) will be true, so the console will display ** x as 10 **. If false
Main.java
int x = 20;
if (x == 10){
System.out.println("x is 10");
}
In the above case, the conditional branch of (x == 10) will be false, so nothing will be displayed on the console. else The else of the if statement can be conditional branching "If ~, OO, otherwise XX".
Main.java
int x = 10;
if (x < 20){
System.out.println("x is less than 20");
} else {
System.out.println("x is greater than 20");
}
In the above case, the result will be displayed as ** x is less than 20 **.
Main.java
int x = 30;
if (x < 20){
System.out.println("x is less than 20");
} else {
System.out.println("x is greater than 20");
}
In the above case, the result will be displayed as ** x is greater than 20 **. else if By combining if, else if, and else, you can create a conditional branch such as "If ~, then ◯◯, if not, then △△, if neither, □□".
Main.java
int x = 25;
if (x < 30){
System.out.println("x is greater than 30");
} else if {
System.out.println("x is greater than 20 and less than 30");
} else {
System.out.println("x is less than 20");
In the above case, the result will be ** x is greater than 20 and less than 30 **. One thing to note is that even if multiple conditions are met, only the first one that is met will be executed.
Conditional branching also has a syntax called a switch statement. The switch statement is executed when the condition value matches the case value.
Main.java
swich(Condition value) {
case value 1:
processing;
break;
case value 2:
processing;
break;
case value 3:
processing;
break;
}
Write as above. After the case is a colon (:). break; is an instruction to end the switch statement. Without break ;, after processing the matching case, the processing of the next case will also be executed. Example of actual code
Main.java
int x=10
swich(x % 2) {
case 0:
System.out.println("Even")
break;
case 1:
System.out.println("Odd")
break;
}
In the above example, ** even ** is executed. default Use default for the process to be executed when it does not match any case. [Example]
Main.java
swich(rank) {
case 1:
System.out.println("First place")
break;
case 2:
System.out.println("2nd place")
break;
case 2:
System.out.println("3rd place")
break;
default:
System.out.println("4th or lower")
break;
}
In the above case, if it is 4th or lower, default will be executed.
Recommended Posts