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

Discussion

Which line will cause a compilation error?

public class Sample93
{
    private char[] grades = {'A', 'B', 'A'};

    int topCount()
    {
        int found = 0;
        for (char g : grades)
        {
            assert g == "A";
            if (g == 'A') found++;
        }
        return found;
    }

    public static void main(String[] args)
    {
        System.out.println(new Sample93().topCount());
    }
}

  • A.assert g == "A";
  • B.if (g == 'A') found++;
  • C.private char[] grades = {'A', 'B', 'A'};
  • D.Nothing here is wrong.

Answer: A

A char cannot be compared with a String; the types are incomparable and the line does not compile. The double quotes make "A" a String object, while the char literal needs single quotes. Changing the comparison to grade == 'A' fixes it.

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

Post your comment

Please log in or register to post a comment.