Given:



public class Calculator {
    public static void main(String[] args) {
        int num = 5;
        int sum;

        do {
            sum += num;
        } while ((num--) > 1);
        System.out.println("The sum is " + sum + ".");
    }
}

What is the result?

A.

The sum is 2

B.

The sum is 14

C.

The sum is 15

D. The loop executes infinite times
E. Compilation fails

題解

第4行宣告了一個sum整數變數,但沒有初始化。第7行的「sum += num;」可以拆解成:

sum = sum + num;

由於sum變數並未初始化就要被取值作加法運算,因此會發生編譯錯誤。