If else statement
The if
statement is a conditional branch statement.
Here is the general form of the if-else
statement:
if (condition)
statement1;
else
statement2;
The else
clause is optional.
Each statement may be a single statement or a compound statement enclosed in curly braces (a block).
The condition is any expression that returns a boolean value.
Only one statement can appear directly after the if
or the else
.
To include more statements, you'll need to create a block, as in this fragment:
public class Main {
public static void main(String[] argv) {
int i = 1;
if (i > 0) {
System.out.println("Here");
i -= 1;
} else
System.out.println("There");
}
}
The output:
Here
It is convenient to include the curly braces when using the if
statement,
even when there is only one statement in each clause.
Nested if statements
A nested if
is an if
statement inside another another if
statement or else
.
public class Main {
public static void main(String[] argv) {
int i = 10;
int j = 4;
int k = 200;
int a = 3;
int b = 5;
int c = 0;
int d =0;
if (i == 10) {
if (j < 20){
a = b;
}
if (k > 100){
c = d;
}
else{
a = c;
}
} else{
a = d;
}
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
The output:
a = 5
b = 5
c = 0
d = 0
The if-else-if Ladder
It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
Here is a program that uses an if-else-if
ladder.
public class Main {
public static void main(String args[]) {
int month = 4;
String value;
if (month == 1 )
value = "A";
else if (month == 2)
value = "B";
else if (month == 3)
value = "C";
else if (month == 4)
value = "D";
else
value = "Error";
System.out.println("value = " + value);
}
}
Here is the output produced by the program:
value = D