public final class Test{
public static void main(String args[]) throws Exception {
BigDecimal bigDecimal_One = BigDecimal.ONE;
System.out.println(bigDecimal_One);
bigDecimal_One.add(BigDecimal.ONE);// 1. As I have not set bigDecimal_One = bigDecimal_One.add(BigDecimal.ONE) hence variable Value would be unchanged
System.out.println(bigDecimal_One);
addTenTo(bigDecimal_One);// 2. I wanted to know why still value is unchanged despite reference pointing to new value
System.out.println(bigDecimal_One);
}
public static void addTenTo(BigDecimal value) {
value = value.add(BigDecimal.TEN);
System.out.println("Inside addTenTo value = "+value);
}
}
当我运行这个程序时,我得到输出
1
Inside addTenTo value = 11
1
有人可以解释为什么变量bigDecimal_One
的值即使在方法addTenTo
中已将参考分配给新值时仍未改变(即11
)吗?
答案 0 :(得分:1)
我的答案是内联......
public static void addTenTo(BigDecimal value) {
value = value.add(BigDecimal.TEN); // `value` here is a local variable, which does not affect the parameter-`value`
System.out.println("Inside addTenTo value = "+value);
}