The If-else statement of Java contains two blocks of code, one for the if and one for the else part. It checks a condition. If the condition is true, then it executes the If block code. If the condition is false, then It executes the else block code.
Syntax
if(condition)
{
//code, will be executed if condition is true
}
else
{
//code, will be executed if condition is false
}
Flowchart
Example 1:
public class Test {
public static void main(String[] args) {
int m = 12; //Defining a variable m
int n = 10; //Defining a variable n
if(m>n) // checking the condition
{
// will execute this code if condition is true
System.out.println(m+" is greater than "+n);
}
else
{
// will execute this code if condition is false
System.out.println(n+" is greater than "+m);
}
}
}
Output
12 is greater than 10
Example 2:
public class Test {
public static void main(String[] args) {
int n = 13; //Defining a variable n
if(n%2==0) // checking the condition
{
// will execute this code if condition is true
System.out.println(n+" "+"is even number");
}
else
{
// will execute this code if condition is false
System.out.println(n+" "+"is odd number");
}
}
}
Output
13 is odd number