Passing objects to methods

When passing objects to methods, only the reference is copied, not the object itself. If the method has access to attributes of the object, it can change the object. This change is preserved after the method returns.

Example

class Person {
    String name;
}

public class PassingObjects {
    static void setName(String n, Person o) {
        o.name = n;
    }
    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();

        setName("John", p1);
        setName("Tom", p2);
        System.out.println(p1.name);
        System.out.println(p2.name);
    }
}
Output