Search code examples
javabigdecimal

To understand BigDecimal class Arithmetic and Object Behaviour


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)?


Solution

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