Java Tutorial-Java Conditions and If statements

Java Conditions and If Statements


Java supports the logical conditions from mathematics.

  • Less than : a < b
  • Less than or equal to : a <= b
  • Greater than : a > b
  • Greater than or equal to : a >= b
  • Equal to : a == b
  • Not equal to : a != b

With the above logical conditions, we can perform different operations for different decisions.

Java has the following conditional statements:

  •    if – the block of statement is executed only if the specified condition is true
  • else – the block of statement is executed, if the same condition is false
  • else if – the new condition to test, if the first condition is false
  •  switch – to specify many alternative blocks of code to be executed


The if statement


The if statement to specify a block of Java code to be executed if a condition is true.


Syntax

if (condition) {
                // block of code to be executed if the condition is true
}

Example

if (10 > 5){
       System.out.println("10 is greater than 5");
}

Output

10 is greater than 5

The else statement


The else statement to specify a block of Java code to be executed if the condition is false.


Syntax

if (condition) {
                // block of code to be executed if the condition is true
} else {
                //block of code to be executed if the condition is false
}

Example

if (10 < 5){
       System.out.println("10 is less than 5");
} else {
       System.out.println("10 is greater than 5");
}

Output

10 is greater than 5

The else if statement


The else if statement to specify a new condition if the first condition is false.


Syntax

if (condition) {
                // block of code to be executed if the condition is true

} else if {
                // block of code to be executed if the first condition is false
} else {
                //block of code to be executed if the previous condition is false
}

Example

if (time < 10){
       System.out.println("Good morning");
} else if (time < 20) {
       System.out.println("Good day");
} else {
       System.out.println("Good evening");
}

Output

Good day

 Ternary Operator ( shorthand if…else)


If there is only one statement to execute, one for if, and one for else, can be put together in a single line.


Syntax

variable = (condition) ? expressionTrue : expressionFalse;

Example

int time = 15;
String result = (time < 18) ? "Good day" : "Good evening";
System.out.println(result);

Output

Good day