JAVA变量作用域
我正在检查一些旧的考试问题,我遇到了一个相当简单的问题,但它不是我所期望的JAVA变量作用域,java,Java,我正在检查一些旧的考试问题,我遇到了一个相当简单的问题,但它不是我所期望的 public class Exampractice { public static void f(int x, int[] y, int[] z) { x = 2; y[0] = x; z = new int[5]; z[0] = 555; } public static void main(String[] args) { int x = 111; int[]
public class Exampractice {
public static void f(int x, int[] y, int[] z) {
x = 2;
y[0] = x;
z = new int[5];
z[0] = 555;
}
public static void main(String[] args) {
int x = 111;
int[] y = {222, 333, 444, 555};
int[] z = {666, 777, 888, 999};
f(x, y, z);
System.out.println(x);
System.out.println(y[0]);
System.out.println(z[0]);
}
}
问题询问以下代码的结果是什么。
我得到以下结果:
111
2
666
我理解为什么x是111,因为局部变量覆盖了所有其他变量,代码上说y[0]=2等于x,x是2,但我不明白为什么z[0]=666,因为它已经在f类中重新排列。该方法创建了一个新的int数组。方法退出后,旧的数组将保持完整。该方法将创建一个新的int数组。在方法退出后,旧的对象是完整的。在Java中,对象引用作为值传递。因此,当
z=newint[5]当执行code>时,f()
方法中存在的局部数组变量z
现在引用新创建的int
数组,并且调用该方法时其引用作为值传递给它的原始数组不会发生任何变化
public static void f(int x, int[] y, int[] z) {
x = 2;
y[0] = x;
// Till here z is referring to the int array passed from main method
z = new int[5]; // now z is re-assigned with a new reference, the one of the newly created int array
// thus the reference to the original array is no more being used here
z[0] = 555; // this modifies the values of the newly created array
}
就个人而言,我总是建议阅读来理解这个概念。在Java中,对象引用作为值传递。因此,当z=newint[5]当执行code>时,f()
方法中存在的局部数组变量z
现在引用新创建的int
数组,并且调用该方法时其引用作为值传递给它的原始数组不会发生任何变化
public static void f(int x, int[] y, int[] z) {
x = 2;
y[0] = x;
// Till here z is referring to the int array passed from main method
z = new int[5]; // now z is re-assigned with a new reference, the one of the newly created int array
// thus the reference to the original array is no more being used here
z[0] = 555; // this modifies the values of the newly created array
}
就个人而言,我总是建议阅读来理解这个概念。因为你在使用创建新对象的new
因为你在使用创建新对象的new
Z是一个新对象,函数中的Z实际上是这个。ZZ是一个新对象,函数中的z实际上是这个。z重要的是值或引用是否设置为变量
x有价值
x=111
及
y和z没有值,它有一个数组的引用
reference y[0] is edited globally in f
z is recreated in the method f locally using "new"
它不会影响main()方法中的原始对象,因此我们得到了该结果。重要的是值或引用是否设置为变量
x有价值
x=111
及
y和z没有值,它有一个数组的引用
reference y[0] is edited globally in f
z is recreated in the method f locally using "new"
它不影响main()方法中的原始对象,因此我们得到了该结果。如果您记住几件事,那么很容易理解它的可能副本:1)在Java中,所有变量都是按值传递的,即,您可以获得原始数据类型的副本和对复杂数据类型的引用的副本。2) new
操作符创建一个全新的对象,它不会更新现有对象。如果您记住几件事,那么很容易理解它的可能副本:1)在Java中,所有变量都是按值传递的-即,您可以获得一个基本数据类型的副本和一个复杂数据类型引用的副本。2) new
操作符创建一个全新的对象,它不会更新现有的对象。我知道它现在是如何工作的了。。。我花了一点时间才弄明白它现在是怎么运作的。。。我花了一点时间才明白过来