0
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);
    }
}

When I run this program I get below Output

1
Inside addTenTo value = 11
1

Could someone please explain why the value of variable bigDecimal_One still unchanged even when reference has been assigned to new Value in the method addTenTo (i.e. 11)?

Shirishkumar Bari
  • 2,692
  • 1
  • 28
  • 36
  • 1
    I think it's pretty well answered here: http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Alexis C. Feb 17 '15 at 09:42

1 Answers1

1

My answer is inline...

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);
}
codeMan
  • 5,730
  • 3
  • 27
  • 51