Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which line will cause a compilation error?

public class Sample86
{
    static int total(int[] values)
    {
        int sum = 0;
        for (int v : values) sum += v;
        return sum;
    }

    public static void main(String[] args)
    {
        int[] scores = {4, 8, 15};
        assert scores.length() == 3;
        System.out.println(total(scores));
    }
}

  • A.No line here is in error.
  • B.assert scores.length() == 3;
  • C.int[] scores = {4, 8, 15};
  • D.for (int v : values) sum += v;

Answer: B

An array exposes length as a field, not a method, so the parentheses make this a call to a method that does not exist and the line fails to compile. The print on the next line shows the correct form. String is the opposite way round, which is what keeps this confusing.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.