News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

Java Tutorial – 08 – Conditionals

Conditional statements are used to execute different code blocks based on different conditions.

If statement

The if statement will only execute if the condition inside the parentheses is evaluated to true. The condition can include any of the comparison and logical operators.

if (x < 1) { 
  System.out.print(x + " < 1"); 
}

To test for other conditions, the if statement can be extended by any number of else if clauses. Each additional condition will only be tested if all previous conditions are false.

else if (x > 1) { 
  System.out.print(x + " > 1"); 
}

The if statement can have one else clause at the end, which will execute if all previous conditions are false.

else { 
  System.out.print(x + " == 1"); 
}

As for the curly brackets, they can be left out if only a single statement needs to be executed conditionally.

if (x < 1)      
  System.out.print(x + " < 1");
else if (x > 1) 
  System.out.print(x + " > 1");
else              
  System.out.print(x + " == 1");

Switch statement

The switch statement checks for equality between an integer and a series of case labels. It then executes the matching case. The statement can contain any number of cases and may end with a default label for handling all other cases.

switch (y) 
{
  case 0: System.out.print(y + " is 0"); break;
  case 1: System.out.print(y + " is 1"); break;
  default:System.out.print(y + " is something else");
}

Note that the statements after each case label are not surrounded by curly brackets. Instead, the statements end with the break keyword. Without the break the execution will fall through to the next case. This can be useful if several cases need to be evaluated in the same way.

The data types that can be used with a switch statement are: byte, short, int and char. As of Java 7, String types are also permitted.

Ternary operator

In addition to the if and switch statements there is the ternary operator (?:). This operator can replace a single if/else clause that assigns a value to a specific variable. The operator takes three expressions. If the first one is evaluated to true then the second expression is returned, and if it is false, the third one is evaluated and returned.

x = (x < 0.5) ? 0 : 1; // ternary operator (?:)
Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours