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.
The Java wrapper types are immutable. Their values never change.
counter++ is really counter = counter + 1; i.e. a new object gets created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With