If-else Statement:
If else statement can be used for executing a group of statements based on condition.
Syntax
if(condition){
statement1; if block
} else{
statement2; else block
}
If the condition is satiesfied then it will be executing if block and if the condition is not satiesfied then it will executing else block.
Program4
class IfElseDemo{
public static void main(String[] args){
int n=89;
if(n%2==0){
System.out.println("Even Number");
}
else{
System.out.println("odd Number");
}
}
}
Rule1: Specifying the condition to if else statement is mandatory and it should be of boolean type( either a condition or boolean variable or boolean value).
Rule2: Specifying the else block is optional
Rule3: Specifying the { } is optional. If we do not specify the { } then it will consider only one statement, and that one statement is mandatory. If we want to consider multiple statements then specifying the { } is mandatory. Within the { } we can specify any number of statements.
Rule4: In If else statement we can not execute both the blocks and we can not skip both the blocks, it will always execute exactly one block.