Java Conditions Operators

Java conditions are also known as Java if-else statement. Java if statement is followed by an optional else statement. The else statement is only executed when the Boolean expression is false.

Syntax:

See the syntax of Java if-else statement.

if (Boolean expression) {
   // It is executed when the Boolean expression is true
}else {
   // It is only executed when the Boolean expression is false
} 

If the Boolean expression is true then the code written in if block is executed, otherwise the code written in else block will be executed.

If-else Flow Diagram

If-else-Flow-Diagram

Let's take a simple example to understand if-else condition in Java language.

If-else Example

/**
 * 
 * @author JavaTportal Corporation
 *
 */
public class Test {
	public static void main(String args[]) {
		int x = 50;
		if (x < 40) {
			System.out.print("This is if statement");
		} else {
			System.out.print("This is else statement");
		}
	}
}

Output-

This is else statement 

If-else....... If-else Statement

The multiple if-else conditions are used to test various conditions. In this condition, if statement is followed by else if... else statement.

You should follow the instructions given below while using if-else... if-else statement:

  • An if can have zero or one else's and it must come after any else if's
  • An if can have zero to many else if's and they must come before the else.
  • Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

if(Boolean_expression 1) {
   // It is executed when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
   // It is executed when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
   // It is executed when the Boolean expression 3 is true
}else {
   // It is executed when none of the above condition is true.
}

Let's take an example to understand the usage of if-else.... if-else Statement in Java language.

						
/**
 * 
 * @author JavaTportal Corporation
 *
 */
public class Test {
	public static void main(String args[]) {
		int x = 30;
		if (x == 10) {
			System.out.print("Value of X is 10");
		} else if (x == 20) {
			System.out.print("Value of X is 20");
		} else if (x == 30) {
			System.out.print("Value of X is 30");
		} else {
			System.out.print("This is else statement");
		}
	}
}

Output-

	
Value of X is 30  	

Next Concept Loops