Java Static Method Parameters

Why 100 100 1 1 1does the following code return , 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 the Hotel by-value parameter seem to use doStuff ()?

+3
source share
5 answers

He does exactly what you told him :-)

Hotel h1 = new Hotel(100);
System.out.print(h1.getRoomNr() + " "); // 100
Hotel h2 = doStuff(h1);
System.out.print(h1.getRoomNr() + " "); // 100 - h1 is not changed, h2 is a distinct new object
System.out.print(h2.getRoomNr() + " "); // 1
h1 = doStuff(h2);
System.out.print(h1.getRoomNr() + " "); // 1 - h1 is now changed, h2 not
System.out.print(h2.getRoomNr() + " "); // 1

( ), Java . h1 doStuff. ( h2), h1 : - 100.

+10

.

+5

Java . Hotel. , Java , h1. h1 .

+4

The hotel link is passed by value. You only change the local variable hotelin the method doStuffand return it without changing the original h1. You can change the source h1of the method if you have the setRoomNr method and is called hotel.setRoomNr(1)though ...

+1
source

Everything is fine. Inside static Hotel doStuff(Hotel hotel)you create an instance new Hotel, the old link Hoteldoes not change.

+1
source

Source: https://habr.com/ru/post/1743214/


All Articles