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

Discussion

What will be the output of the program?

interface Count 
{
    short counter = 0;
    void countUp();
}
public class TestCount implements Count 
{
    public static void main(String [] args) 
    {
        TestCount t = new TestCount();
        t.countUp();
    }
    public void countUp() 
    {
        for (int x = 6; x>counter; x--, ++counter) /* Line 14 */
        {
            System.out.print(" " + counter);
        }
    }
}

  • A.0 1 2
  • B.1 2 3
  • C.0 1 2 3
  • D.
    1 2 3 4
  • E.Compilation fails

Answer: E

Correct answer: Compilation fails

Every field declared in an interface is implicitly public static final, so counter is a constant. The loop’s ++counter attempts to assign to it, which the compiler rejects. The comparison x>counter would have been perfectly legal - reading a constant is fine - and it is the attempt to modify it that fails.

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

Post your comment

Please log in or register to post a comment.