Java Else Keyword

Java Else Keyword


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 -
  1.  Only if
  2. If ___  else
  3. else__if  ladder
  4. Multiple if
  5. 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 - 
a is not equal to b
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