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

Discussion

What will be the output of the program?

public class Test 
{
    public int aMethod()
    {
        static int i = 0;
        i++;
        return i;
    }
    public static void main(String args[])
    {
        Test test = new Test();
        test.aMethod();
        int j = test.aMethod();
        System.out.println(j);
    }
}

  • A.00
  • B.1
  • C.2
  • D.Compilation fails

Answer: D

Correct answer: Compilation fails

Java has no local static variables. The keyword static may qualify a field, a method, a nested class or an initialiser block, but never a variable declared inside a method - a local variable’s lifetime is the invocation, and a static lifetime would contradict that. The declaration is rejected at compile time, so nothing runs and the question of what would be printed does not arise.

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

Post your comment

Please log in or register to post a comment.