Review Questions

graphics/rq_icon.gif

5.1

What will be the result of attempting to compile and run the following class?

public class IfTest {
    public static void main(String[] args) {
        if (true)
        if (false)
        System.out.println("a");
        else
        System.out.println("b");
    }
}

Select the one correct answer.

  1. The code will fail to compile because the syntax of the if statement is incorrect.

  2. The code will fail to compile because the compiler will not be able to determine which if statement the else clause belongs to.

  3. The code will compile correctly and display the letter a when run.

  4. The code will compile correctly and display the letter b when run.

  5. The code will compile correctly, but will not display any output.

5.2

Which statements are true?

Select the three correct answers.

  1. The conditional expression in an if statement can have method calls.

  2. If a and b are of type boolean, the expression (a = b) can be the conditional expression of an if statement.

  3. An if statement can have either an if clause or an else clause.

  4. The statement if (false) ; else ; is illegal.

  5. Only expressions which evaluate to a boolean value can be used as the condition in an if statement.

5.3

What, if anything, is wrong with the following code?

void test(int x) {
    switch (x) {
        case 1:
        case 2:
        case 0:
        default:
        case 4:
    }
}

Select the one correct answer.

  1. The variable x does not have the right type for a switch expression.

  2. The case label 0 must precede case label 1.

  3. Each case section must end with a break statement.

  4. The default label must be the last label in the switch statement.

  5. The body of the switch statement must contain at least one statement.

  6. There is nothing wrong with the code.

5.4

Which of these combinations of switch expression types and case label value types are legal within a switch statement?

Select the one correct answer.

  1. switch expression of type int and case label value of type char.

  2. switch expression of type float and case label value of type int.

  3. switch expression of type byte and case label value of type float.

  4. switch expression of type char and case label value of type long.

  5. switch expression of type boolean and case value of type boolean.