First example. 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.
Info 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.
Tip 2 To compare a number, we use 2 equals signs. This is an expression. It evaluates to a true or false result.
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
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."
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!
And, or. 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.
And With OR, only one expression must be true. After the first true evaluation, nothing further is tested.
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 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.
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).
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
True and false. A boolean variable can equal true or false. We can test expressions and variables with the true or false keywords.
Note The exclamation means "not." So using !occupied will evaluate to true only if "occupied" is set to 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);
}
}
}true
Method call. 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
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.
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...
Benchmark, reorder. 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.
Result The optimized, most-common-first order is faster. We use heuristics, or frequency analysis, to optimize 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
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.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 11, 2023 (edit).