首页 > 解决方案 > Consider the following program written in Java. why this output **2 2**. I think this should be output **1 1**

问题描述

Consider the following program written in Java. Why is the output 2 2? I think it should output 1 1

class Access{
  static int x;
  void increment(){
    x++;
  }
}

public class Main{
  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);
  }
}

标签: java

解决方案


静态变量在类的所有实例之间共享,当我们需要进行内存管理时它们很有用。在某些情况下,我们希望所有实例都有一个共同的值,比如全局变量,那么最好将它们声明为静态,因为这样可以节省内存(因为只为静态变量创建单个副本)。

因此,当调用 obj1.increment() 时,它会将 x 的值更新 1。当调用 obj2.increment() 时,它会将相同的静态引用更新 +1 并使其变为 2。最后,ypu 将两个值都设为2. 下面的代码片段会将值打印为 1 和 2。

obj1.increment();
System.out.println(obj1.x);
obj2.increment();
System.out.println(obj2.x);

推荐阅读