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.
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:
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.