Why does the following code return 100 100 1 1 1 and not 100 1 1 1 1 ?
public class Hotel {
private int roomNr;
public Hotel(int roomNr) {
this.roomNr = roomNr;
}
public int getRoomNr() {
return this.roomNr;
}
static Hotel doStuff(Hotel hotel) {
hotel = new Hotel(1);
return hotel;
}
public static void main(String args[]) {
Hotel h1 = new Hotel(100);
System.out.print(h1.getRoomNr() + " ");
Hotel h2 = doStuff(h1);
System.out.print(h1.getRoomNr() + " ");
System.out.print(h2.getRoomNr() + " ");
h1 = doStuff(h2);
System.out.print(h1.getRoomNr() + " ");
System.out.print(h2.getRoomNr() + " ");
}
}
Why does it appear to pass Hotel by-value to doStuff() ?
It does exactly what you told it to do 🙂
As others noted (and is explained very clearly in this article), Java passes by value. In this case, it passes a copy of the reference
h1todoStuff. There the copy gets overwritten with a new reference (which is then returned and assigned toh2), but the original value ofh1is not affected: it still references the first Hotel object with a room number of 100.