Java null object

advertisements

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 71 answers

So as far as I know, in java you can't access objects directly, you only have the pointer to it. So for example I have this code:

public class App {
    public App() {
        Thing t = null;
        doStuff(t);
        System.out.println(t);
    }

    public void doStuff(Thing a) {
        a = new Thing();
    }

    public static void main(String[] args) {
        new App();
    }
}

class Thing { }

And the output is null. Why? I've passed the pointer to a method which gave it a new Thing instance to point to. Is it because it's a new pointer? Also how can I resolve it without returning anything from doStuff()?


You have references not pointers, and a method cannot update the callers reference without an assignment in the caller - so this

public App() {
    Thing t = null;
    doStuff(t);
    System.out.println(t);
}

public void doStuff(Thing a) {
    a = new Thing();
}

Would work if you did,

public App() {
    Thing t = null;
    t = doStuff(t);
    System.out.println(t);
}

public Thing doStuff(Thing a) {
    a = new Thing();
    return a;
}