< Java Tutorial

Java if-else

← Previous Next →

Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Java programming language provides following types of decision making statements.

Sr.No. Statement & Description
1 if statement
An if statement consists of a boolean expression followed by one or more statements.
2 if...else statement
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
3 nested if statement
You can use one if or else if statement inside another if or else if statement(s).

If Statement


if(condition) { // condition like x > 10 
  // if condition is true then all the code here will be executed

If Else Statement 


if(condition1) {
   // code block 1 
} else if ( condition2 ) { 
   // code block 2 
} else { 
  // code block 3 

Nested If Statments


if(condition) {
   // code 1
   if(inner_condition) {
	// code 2	
   } else {
        // code 3		

The ? : Operator

We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

To determine the value of the whole expression, initially exp1 is evaluated.

1.If the value of exp1 is true, then the value of Exp2 will be the value of the whole expression.

2.If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression.

← Previous Next →