Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Why value of primitive wrapper class (e.g. Integer) isn't maintained in recursive calls?

Tags:

java

recursion

I am using recursion and I want an Integer object to retain its value across recursive calls. e.g.

public void recursiveMethod(Integer counter) {
    if (counter == 10)
        return;
    else {
        counter++;
        recursiveMethod(counter);
    }
}

public static void main(String[] args) {
    Integer c = new Integer(5);
    new TestSort().recursiveMethod(c);
    System.out.println(c); // print 5
}

But in the below code (where I am using a Counter class instead of Integer wrapper class, the value is maintained

public static void main(String[] args) {
    Counter c = new Counter(5);
    new TestSort().recursiveMethod(c);
    System.out.println(c.getCount()); // print 10
}

public void recursiveMethod(Counter counter) {
    if (counter.getCount() == 10)
        return;
    else {
        counter.increaseByOne();
        recursiveMethod(counter);
    }
}

class Counter {

    int count = 0;

    public Counter(int count) {
        this.count = count;
    }

    public int getCount() {
        return this.count;
    }

    public void increaseByOne() {
        count++;
    }
}

so why primitve wrapper class behaves differently. After all, both are objects and in the reucrsive call, I am passing the Integer object and not just int so that Integer object must also maintain its value.

like image 415
Yatendra Avatar asked Mar 26 '26 15:03

Yatendra


1 Answers

The Java wrapper types are immutable. Their values never change.

counter++ is really counter = counter + 1; i.e. a new object gets created.

like image 167
Oliver Charlesworth Avatar answered Mar 29 '26 04:03

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!