What will be the output of the following Java program? [code] class access { static int x; void increment()

What will be the output of the following Java program?
Code:
    class access
    {
       static int x;
       void increment()
       {
           x++;
       }   
     }   
    class static_use 
    {
        public static void main(String args[])
        {
            access obj1 = new access();
            access obj2 = new access();
            obj1.x = 0;   
            obj1.increment();
            obj2.increment();
            System.out.println(obj1.x + " " + obj2.x);
         }
   }
A. 1 2
B. 1 1
C. 2 2
D. Compilation Error
 
Answer: c
Explanation: All objects of class share same static variable, all the objects share same copy of static members, obj1.x and obj2.x refer to same element of class which has been incremented twice and its value is 2.
output:
Code:
$ javac static_use.java
$ java static_use 
2 2
 

Tìm kiếm

Back
Top