Tech and Media Labs
This site uses cookies to improve the user experience.




Java if statements

Jakob Jenkov
Last update: 2015-03-02

The Java if statement enables your Java programs to make decisions about what code to execute depending on the state of variables, or values returned from methods. Here is a simple Java if example:

boolean isValid = true;

if ( isValid ) {
    System.out.println("it is valid");
} else {
    System.out.println("it is not valid");
}

The if statement in this example tests the boolean variable isValid and based on its value (either true or false) it executes one of two different blocks of code. If the isValid variable has the value of true, the first block is executed. If not, the code inside the else block is executed.

The expression inside the parentheses is called the condition. The condition can be any Java expression, as long as the result of the expression is a boolean result (either true or false).

In the example above, the condition was whether the isValid variable was true or false.

If the block of code to be executed is just a single statement, you do not need the brackets { } around them, in the if statements. Here is an example:

if ( isValid )   System.out.println("it is valid");
else             System.out.println("it is not valid");

However, it is good practice to put the brackets around the statements, even if there is only one statement to execute. Often during development you may start with a single statement that needs to be executed inside an if or else block, but later have to add more statements to the blocks. This can lead to errors that are hard to spot. Look at this if statement:

if( isValid)
    System.out.println("it is valid");

Now imagine I have to increment a valid counter if isValid is true. Naively I might change the code to this:

if( isValid)
    validCount++;
    System.out.println("it is valid");

But now only the validCount++ statement belongs to the if statement. The System.out.println() statement will always be executed. Or, imagine if I had switched the statements like this:

if( isValid)
    System.out.println("it is valid");
    validCount++;

Now only the System.out.println() statement belongs to the if statement. The validCount++ statement will always be executed.

To avoid this error I almost always put the brackets around the blocks to execute, even if there is only one statement to execute in the block. Here is how that could look:

if ( isValid ) { System.out.println("it is valid");  }
else           { System.out.println("it is not valid"); }

When the brackets are there, it is easier to remember to insert new statements inside the brackets.

Conditional Operators

Java has a set of conditional operators you can use, which result in a value of either true or false. These are:

  • ==
  • !=
  • <
  • <=
  • >
  • >=

The == operator tests if two values are equal to each other. For instance:

long var1 = 2;
long var2 = 5;

if(var1 == var2) {
   //...
}

If the two variables, var1 and var2, are equal, the expression var1 == var2 is evaluated to true. Otherwise the expression is evaluated to false.

The != operator does the exact opposite of the == operator. If the two variables are not equal, the expression is evaluated to true. If the two variables are equal, the expression is evaluated to false.

The < operator is evaluated to true, if the variable on the left side of the operator is less than the variable on the right side of the operator. If the left variable is equal to, or larger, the expression is evaluated to false. Here is an example expression:

if(var1 < var2) {
   //...
}

The <= operator works like the < operator, except it also evaluates to true if the two variables are equal to each other, and false otherwise.

The > operator works the exact opposite way of the < operator. The operator expression is evaluated to true if the variable on the left side of the operator is greater than the variable on the right side of the operator, and false if not. Here is a simple example:

if(var1 > var2) {
   //...
}

The >= operator works like the > operator except it also evaluates to true if the two variables are equal to each other.

Comparing Variables and Constants

In the examples earlier in this text I have only shown comparisons of either constants to constants, or variables to variables. But, you can also compare constants to variables. Here are two examples:

int var1 = 50;

if(var1 > 10) {
   //...
}

if(99 <= var1) {
   //...
}

Methods as Conditions

You can also use the return value of a method as condition in an if statement. Here is how:

public void methodOne (String input) {

    if ( isValid(input) ) {
        System.out.println(input + " is valid");
    } else {
        System.out.println(input + " is not valid");
    }

}

public boolean isValid(String value) {
    if( value.equals("123") ) {
        return true;
    }
    return false;
}

This example actually contains two if statements with methods as conditions. First the

 if( isValid(input) )

which tests the output of the isValid(input) method, for a true or false result.

Second, inside the isValid() method the String.equals() method is used to test for equality to a certain string value. This is the if statement that tests it:

if( value.equals("123") ) {

The isValid() method could actually have been written in a shorter way. Here is how:

public boolean isValid(String value) {
    return value.equals("123");
}

Now the isValid() method returns the value returned by the value.equals() method call.

You could also switch the string "123" and value variable in the statement, like this:

public boolean isValid(String value) {
    return "123".equals(value);
}

This version actually has the advantage, that if value is null (does not point to a String object, but to nothing), this version will not result in a NullPointerException .

Chaining if Statements

It is possible to chain if statements, to create a decision tree. Here is an example:

if( name.equals("john")) {
    //...
} else if ( name.equals("jane")) {
    //...
} else if ( name.equals("Linda")) {
    //...
} else {
    //...
}

In the example above, else if statements are chained, one after another. Actually, this chained if statement is just an if statement executed in an else block, without the brackets { }, as I showed you that you can, in the beginning of this text. The above code is actually equivalent to this:

if( name.equals("john")) {
    //...
} else {
    if ( name.equals("jane")) {
        //...
    } else {
        if ( name.equals("Linda")) {
            //...
        } else {
            //...
        }
    }
}

As you can see, the first version is actually easier to read. This is the one exception I normally have to the rule of always embedding the statements of the if and else inside brackets. In this case I prefer the first version. It is easier to read, write, and does not often result in programming errors.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC