In Java we use an if
-statement (with optional "elses") to make decisions. We use expressions and operators—these things affect performance.
An important consideration with if
-statements is the ordering of tests. If we place the most common first, we can speed up our program.
This program uses the if
-statement in a loop. It also includes else
-if and else blocks. The for
-loop iterates through the values 0, 1 and finally 2.
else
-statement here catches all cases not yet matched. The value 2, unmatched, ends up in the else
-statement.System.out.println
method, with a String
argument, to display results to the console.public class Program { public static void main(String[] args) { // Loop through three numbers. for (int i = 0; i <= 2; i++) { if (i == 0) { System.out.println("Zero"); } else if (i == 1) { System.out.println("One"); } else { System.out.println("Else reached"); } } } }Zero One Else reached
To compare two numbers for inequality, we use the "!=" operator. We can also negate an entire expression by using a leading exclamation mark and parentheses.
public class Program { public static void main(String[] args) { int value = 5; // This expression... if (value != 6) { System.out.println("Not 6!"); } // Is the same as this one. if (!(value == 6)) { System.out.println("Not 6!"); } } }Not 6! Not 6!
Often we chain expressions within an if
-statement. We can use binary (two-part) operators for this. With AND both expressions must evaluate to true.
public class Program { public static void main(String[] args) { int width = 10; int height = 5; // Both expressions must evaluate to true. if (width == 10 && height == 5) { System.out.println("width 10 and height 5"); } // Only one expression must be true. if (width == 100 || height > 0) { System.out.println("width 100 or height greater than 0"); } } }width 10 and height 5 width 100 or height greater than 0
Boolean
, store expressionsIf
-statements can become complex. Often an expression is repeated. We can store the result of an expression in a boolean, and then just test that.
bool
can help reduce calls (and improve performance).public class Program { public static void main(String[] args) { int width = 10; int height = 15; int weight = 200; // Use a boolean to store computed result. boolean fits = width <= 10 && height <= 20; // We can use the boolean, not a complex expression. if (fits && weight <= 150) { System.out.println("It fits"); } else { System.out.println("Does not fit"); } } }Does not fit
A boolean variable can equal true or false. We can test expressions and variables with the true or false keywords.
public class Program { public static void main(String[] args) { boolean vacant = true; boolean occupied = false; // Test boolean variables. if (vacant && !occupied) { System.out.println(true); } } }true
Often we call methods in if
-statements. In this example we test for an odd number. We can read the if
-statement as: "if is odd number."
public class Program { static boolean isOdd(int value) { // See if number is not evenly divisible by 2. return (value % 2) != 0; } public static void main(String[] args) { int number = 5; // Call method in if-statement. if (isOdd(number)) { System.out.println(true); } } }true
An expression in an if
-statement must be evaluated to a boolean. In this program, we try to test an int
, but this does not evaluate to true or false. It causes an error.
public class Program { public static void main(String[] args) { int value = 1; // This does not compile: we must have a boolean expression. if (value) { System.out.println(1); } } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to boolean...
Ifs are sequentially evaluated. The first expression is tested first. We can exploit this to optimize if
-statement execution.
String
against the literals "tea" and "java." The String
equals "java" so evaluation continues until "java" is tested.if
-statements.public class Program { public static void main(String[] args) { String value = "java"; int count = 0; long t1 = System.currentTimeMillis(); // Version 1: if-statements ordered most common last. for (int i = 0; i < 100000000; i++) { if (value == "tea") { count++; } else if (value == "java") { count += 2; } if (count == 0) { System.out.println(false); } } long t2 = System.currentTimeMillis(); // Version 2: if-statements ordered most common first. for (int i = 0; i < 100000000; i++) { if (value == "java") { count += 2; } else if (value == "tea") { count++; } if (count == 0) { System.out.println(false); } } long t3 = System.currentTimeMillis(); // ... Benchmark times. System.out.println(t2 - t1); System.out.println(t3 - t2); } }35 ms: unoptimized order 32 ms: optimized order
In this kind of expression, we can assign a variable (or return a value) based on a condition. A ternary requires the question mark and ":" operators.
The if
-statement, and its friends else
-if and else, are important constructs. In Java, they are part of nearly every program. We use them for simple and complex selections.