We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

General

if else statement in Java

if else statement in Java

if else statement in Java

This is part of looping in java. It provides additional functionality to if loop. If the condition for if loop is not correct, it will go to else block. We can not provide condition to else block. In if else loop only one will be executed at a time but it depends on the condition given in if loop.

Syntax:

if(condition)
{ //statements, when condition is true
}
else
{
//statements, when condition is false
}

Example:

public class LoopingInIfElse {      
       public static void main(String[] args) {  
           //defining a variable  
           int number=13;  
           //Check if the number is divisible by 2 or not  
           if(number%2==0){  
               System.out.println("even number");  
           }else{                 
               System.out.println("odd number"); 
           }  
       }  
}

Here if the condition in if block holds true, in this case it is not true. That’s why it will got to else block.

else if Statement

Since we can not give condition in else block, need arises for multiple conditioning. We can give multiple conditions using else if. We can use else if after if and before else. Else has to be the last block while using else if.

Example:

package folwOfControl;
public class LoopingIfLadder {     
       public static void main(String[] args) { 
           String a="Besant";     
           if(a.equals("neha")){
              System.out.print("Success in if");
           }
           else if(a.equals("Besant")){
              System.out.print("Success in elseif");
           }
           else{
              System.out.print("failure");
           }
       } 
}

Points to Remember:

  • Once program control execute any of else if block, it will not go further to else if or else block.
  • While using if or else if block else block is optional.
  • We can not give condition in else block.
  • We can use if block inside an if block.

Click Here-> Get Java Training with Real-time Projects

Besant Technologies WhatsApp