If....Else in Java

If....Else in Java

Hello everyone! Today in this article, we will see the "if.....else" statement in Java. This statement is conditional, it means it checks the condition first and then proceeds to execution. For eg, Suppose you went to a shop for buying some stuff. For buying it, you will first check the condition of that stuff and then you will go for it. The same is with 'if-else ' in java. It first checks the condition and then moves forward. Let us see the syntax of the if-else.

if(condition){
     //code to be executed 
}
else{
       //code to be executed 
}

You might be thinking that how it works? So here is the example.

int x=10;
int y=20;
if(x<y){
     System.out.println("x is less than y");
}
else{
 System.out.println("x is greater than y");
}
//Output:-  x is less than y

In the above code, when the if's condition becomes true then the code inside the if statement is executed. If the code inside the if statement is not executed obviously it will execute the code inside the else part. Similarly, if you have to check multiple conditions then we use the else-if ladder. Now, what's that? See the below code you will get it clearly.

int x=10;
int y=10;
if(x<y){
     System.out.println("x is less than y");
}
else if(x==y){
     System.out.println("x is equal to y");
}
else{
     System.out.println("x is greater than y");
}

//Output:-  x is equal to y

In the above code, you will see that there is an else-if ladder. The code executes in the following way: First, it checks the if's condition(in the above code it is if(x<y)) if it is true then the code inside the if statement is executed if it is false, it moves forward to another if's condition(in the above code it is if(x==y)) if it is found true it will execute the code. Otherwise, it will execute the else part.

Important-Note: The last else part is of the last if statement used.

Note: If you have to check only one condition, you can use only the if statement.

if(5<6){
        System.out.println("You are inside the if statment");
}

//Output:- You are inside the if statement

Hope you have understood today's topic. If you facing any difficulties, feel free to ask in the comment section. Happy Programming! Thanks for your time.

For summary:

java-if-else-if-control-statements-syntax.jpg

Did you find this article valuable?

Support ProgrammingForEveryone by becoming a sponsor. Any amount is appreciated!