问题描述
我知道java中的一切都是按值传递的,但下面的代码不应该打印2而不是1.
I know that everything in java is passed by value but shouldn't the below code print 2 instead of 1.
我所做的只是传递 Integer
并更改其值.为什么打印 1 而不是 2 ?
All I am doing is passing Integer
and changing its value. Why is it printing 1 instead of 2 ?
public static Integer x;
public static void doChange(Integer x) {
x = 2;
}
public static void main(String arg[]) {
x = 1;
doChange(x);
System.out.println(x);
}
推荐答案
非常感谢您的回答.我想我现在知道幕后发生了什么.我认为我看不到 main 函数变化的原因是整数是不可变的,当我为其分配新值时,它会创建新对象并分配给引用 x;
thank you so much for your answers. i think i know now what is happening under the hood. i think the reason i am not able to see changes in main function is because integer is immutable and when i am assigning new value to it, its creating new object and assigning to the reference x;
如果我们可以用可变数据重复相同的例子,我们会看到不同的输出.
if we can repeat same example with mutable data we ll see different output.
public static StringBuilder x;
public static void doChange(StringBuilder x)
{
x.append("world");
}
public static void main(String arg[]) {
x = new StringBuilder("hello ");
doChange(x);
System.out.println(x);
}
输出:你好世界
这篇关于函数不会改变java中变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!