Java OCA OCP Practice Question 799


What is the result of compiling and executing the following application?

package mypkg; /*  ww w . j  a v a2 s  . c  o m*/
public class Main { 
   static int c; 
   double scaleToughness; 
   public Main() { 
   public void m(int c) { 
      System.out.print(c+" "); 
   public static void main(String[] unused) { 
      new Main().m(c); 
      new Main().m(c); 
  • A. 0 1
  • B. 1 1
  • C. 1 2
  • D. 2 2
  • E. The code does not compile.
  • F. The code compiles but produces an exception at runtime.



The code compiles and runs without exception, making Options E and F incorrect.

The question is testing your knowledge of variable scope.

The c variable is static in the Main class, meaning the same value is accessible from all instances of the class, including the static main() method.

The static variable c is incremented each time the constructor is called.

Since c is a local variable within the m() method, the argument value is used, but changes to the local variable do not affect the static variable c.

Since the local variable c is not used after it is decremented, the decrement operation has no meaningful effect on the program flow or the static variable c.

Since the constructor is called twice, with m() executed after each constructor call, the output printed is 1 2, making Option C the correct answer.