TheDeveloperBlog.com


Java

Java If-Statements, Expressions

If-statement. This evaluates an expression. If the evaluation is true, the code inside the block is reached. Otherwise an else-if or else-statement is tested.


Expressions. If-statements are used in many programs. We use operators, binary and unary, in their expressions. A binary operator has two operands. A unary, one.


If, else. 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: The else-statement here catches all cases not yet matched. The value 2, unmatched, ends up in the else-statement.

Tip: We call the System.out.println method, with a String argument, to display results to the console.

Console
Based on:

Java 7

Java program that uses if-statement

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");
	    }
	}
    }
}

Output

Zero
One
Else reached

Comparison operator. To compare a number, we use two equals signs. This is an expression. It evaluates to a true or false result. Comparisons are not the same as assignments.


Negation. 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.

Tip: Sometimes it is easier to negate an entire expression. This can be read as "if not."

Java program that uses not equals

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!");
	}
    }
}

Output

Not 6!
Not 6!

And, or. Often we chain expressions within an if-statement. We can use binary (two-part) operators for this. With && both expressions must evaluate to true.

And: With ||, only one expression must be true. After the first true evaluation, nothing further is tested.

Java program that uses and, or

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");
	}
    }
}

Output

width 10 and height 5
width 100 or height greater than 0

Boolean, store expressions. If-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.

Boolean

Note: Imagine the "fits" boolean was tested many times. It would make the program simpler.

Note 2: If a time-consuming method call is part of an if, storing its result in a bool can help reduce calls (and improve performance).

Java program that uses boolean

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");
	}
    }
}

Output

Does not fit

True and false. A boolean variable can equal true or false. We can test expressions and variables with the true or false keywords.

Exclamation: This means "not." So using !occupied will evaluate to true only if "occupied" is set to false.

Java program that uses true, false

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);
	}
    }
}

Output

true

Reorder if-statements. Ifs are sequentially evaluated. The first expression is tested first. We can exploit this to optimize if-statement execution.

Here: We test a String against the literals "tea" and "java." The String equals "java" so evaluation continues until "java" is tested.

Version 1: This is the unoptimized version. It tests "tea" before "java" so two comparisons always occur.

Version 2: This version tests the most common condition first. So it incurs half as many total checks.

Tip: Check most common conditions first. We use heuristics, or frequency analysis, to optimize if-statements.

Java program that times if-statement reordering

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);
    }
}

Results

35 ms:  unoptimized order
32 ms:  optimized order

Type mismatch. 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.

Java that causes type mismatch

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);
	}
    }
}

Output

Exception in thread "main" java.lang.Error:
    Unresolved compilation problem:
    Type mismatch: cannot convert from int to boolean...

Switch. Another option is the switch-statement. With switch, we cannot use complex expressions, only constants. This is a slightly different concept.

Switch

Ternary. 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.

Ternary Operator

Constructs. 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.