Else Keyword In Java
-
Use if to specify a block of code to be executed, if a specified condition is true
-
Use else to specify a block of code to be executed if the same condition is false.
Note -
1. Else is an optional part
2. Condition is mandatory with if
3. We can not specify any condition with else.
If else has total 5 different variations which we will see as follows -
- Only if
- If ___ else
- else__if ladder
- Multiple if
- Nested if.
All of the above-mentioned conditional constructs can use an else statement as an optional part.
Now we will see some Examples -
Example -
int a= 7;
int b = 9;
if (a == b) {
System.out.println("a is equal to b");
}
else {
System.out.println("a is not equal to b");
}
|
Output - A sample output would be -
Example - We will modify the previous example a little bit.
int a= 7;
int b = 9;
if (a == b) {
System.out.println("a is equal to b");
}
else if(a>b){
System.out.println("a is greater then b");
}
else {
System.out.println("a is smaller then b");
}
|
Output -
Output :
a is smaller then b
|