Resources‎ > ‎Java Basics‎ > ‎

Conditional Statements

Conditional statements allow the programmer to specify that a block of code should only be executed if a particular condition is met. 

if

The syntax of an if statement in Java is as follows:
if (condition) {
    //one or more statements
}

A few comments about the syntax above:
  • if is a keyword 
  • The condition is surrounded by parentheses
  • The block of statements to be executed is surrounded by curly braces
    • If you only have 1 statement in the body of your if, you may omit the curly braces.  It is recommended that you always use them.
  • It is good coding style to indent the body of your if, but it is not required by the Java compiler.  It is, however, required by the instructor!
You may also follow an if with an else, and nest if-else statements as follows:
if(score > 90) {
    System.out.println("A");
} else {
    if(score > 80) {
        System.out.println("B");
    } else {
        if(score > 70) {
            System.out.println("C");
        } else {
            System.out.println("F");
        }
    }
}
    
As the example above demonstrates, it can get quite messy to test several conditions.  The above code can also be written as shown below using else if conditions.
if (x > 90) {
    System.out.println("A");
} else if (x > 80) {
    System.out.println("B");
} else if (x > 70) {
    System.out.println("C");
} else {
    System.out.println("F");
}
Following an if, you may have 0 or more else ifs and 0 or 1 else.

Once a condition is satisfied, the rest will not be tested.  In the example above, if score is 94, the first condition will be true, the program will print A, and skip the remaining else ifs.

The boolean operators && and || are used to chain together multiple conditions.  For example, to determine whether a particular string contains the characters x, y and z, y, you might do the following:
if(s.contains("a") && s.contains("b") && s.contains("c")) {
    //statements
}


Comments