Video in progress

Junior ☕ Core Java

In Java, are arguments passed to a method "by value" or "by reference"?

Always by value. When you pass an object, a copy of the reference is passed: the method can change the inside of the object, but it can't make the caller's variable point to a different object.

📖 Answer

static void rename(User u) {
    u.setName("Aziz");      // the object's contents change: the caller sees it too
    u = new User("Bobur");  // only the local copy points to another object
}

User user = new User("Ali");
rename(user);
System.out.println(user.getName()); // Aziz

The u inside the method is a copy of the user reference. Since both point to the same object, setName is visible. u = new User(...) only changes the copy.

That's why you can't write a swap(a, b) method in Java like you can in C++.

This is where people often slip up in interviews: saying "objects are passed by reference" is wrong. The correct phrase is "references are passed by value".