Java – If else

If-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:

  1. if statement
  2. if-else statement
  3. 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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan