5 years working with Java, got big surprise today with "Pass by value"

java

Dec 31 2023 14:51

Today I saw a simple Java exam question about OOP Before it, I knew stack and heap and the Java rule everything pass by value. And value means the reference address stores in stack, not the object in heap.

Let have a look at this question:
public class Tester {
    public static Person checkPerson(Person p) {
        if (p == null) {
            p = new Person("Joe");
        } else {
            p = null;
        }
        return p;
    }

    public static void main(String[] args) {
        Person p = null;
        checkPerson(p);
        System.out.print(p);
        p = new Person("Mary");
        checkPerson(p);
        System.out.print(p);
    }
}

class Person {
    private String name;
    public Person(String name) {
        this.name = name;
    }
    public String toString() {
        return name;
    }
}
Answer
  • A) Joenull
  • B) nullnull
  • C) Marynull
  • D) nullMary

The checkPeson() method logic

if (p == null) {
    p = new Person("Joe");
} else {
    p = null;
}

ah ha, the first print must be "Joe" cause we pass a null to it right away select the Answer A - Joenull without any hesitate, but correct answer is D) nullMary Wait, what? the first print is null. But we have p = new Person("Joe") already in the method?I start to doubt about did Java pass the reference of object to the method?

After some crazy search on internet, I finally understand why, "everything pass by value" mean a copy of reference address value (not the real reference value)

The parameter I pass to the method is a clone of the real one, it's a local variable (a variable that's declared within the body of a method)

The real one still points to a null value, it got no effect after the method execute That why we have correct answer nullMary

Oh what a shame, after 7 years in Software Development and 5 years with Java, Sometime thing I am a senior but everything collapse after this.

Couldn't believe I lacked this important point

My excuse
  • I have learn many languages whenever my company have a new project (or when I land new job). Learn Java at university, first job with C#, then Ruby, VBA and final comeback with Java
  • As a fullstack developer, I use 50% time working with Style and client events (javascript, JQuery)
  • Lazy reading technical document, always prefer short explain and blog cause all I want is make code run as soon as possible

The way I am working is still good, customers love that problem solve quickly and I'm like a superstar in my team But for me, it's time to slow down, learn the concept instead of google for code and use Trial-error method Discussion here: 5 years working with Java, got big surprise today with "Pass by value"

me

Pham Duc Minh

Da Nang, Vietnam