Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what is the difference between the following declarations?

Tags:

java

Considering Java. How are these 2 different and why?

public void languageChecks() {
    Integer a = 5;
    Integer b = new Integer(5);

    change(a); // a doesn't get incremented. value is 5
    change(b); // b does. value is now 6
}

public void change(Integer a) {
    a++;
}
like image 560
EFreak Avatar asked Apr 09 '26 08:04

EFreak


1 Answers

The only difference is that

Integer b = new Integer(5);

guarantees a new object is created. The first will use an instance from a cache (see Integer.valueOf()).

Both are immutable and the references to both are passed by value (as is everything in Java). So change() has no effect on either.

like image 184
Mark Peters Avatar answered Apr 11 '26 21:04

Mark Peters



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!