If-else
If and else use to apply logical mathematical conditions. This will return true or false after statement execution.
Below are some conditions:
a < b : a is less than b.
a > b : a is greater than b
a == b : a is equal to b
a >= b : a is greater than equal to b
a <= b : a is less than equal to b
a != b : a does not equal to b
There are different if else statements in Java:
- if statement
- if-else statement
- nested else-if statements
If Statement:
The if statement decides either to run or not the block of code.
Example:
myMethod() -> called two times with different value 1 and 10. But, the output print only once.
Get Imran Khan’s stories in your inbox
Join Medium for free to get updates from this writer.
myMethod(1) -> This will execute the block of code and print “a is less than 5” as a is less than 5, where the value of a is 1.
myMethod(10) -> This will not execute the block of code as a is greater than 5, where the value of a is 10.
else Statement:
This will always be coming with if statement. The else statement block of code will execute once if condition returns false.
Example:
myMethod(1) -> This will execute the block of code and print “a is less than 5” as a is less than 5, where the value of a is 1.
myMethod(10) -> This will execute else statement block of code “a is greater than 5” as a is greater than 5, where the value of a is 10.
else If statement:
This will add more conditions to check if the first condition if false.
sum(5) -> This will execute else if statement block of code as “a is equals to 5” and print “a is equal to 5”
Short hand if and else or Ternary Operator:
This is also known as short hand if and else. It converts multiple lines of code in single.
Syntax:
I hope you found out this article interesting and informative. Please share it with your friends to spread the knowledge.
You can follow me for upcoming blogs follow.
Thank you!







