-2

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()?

RuntimeException
  • 193
  • 1
  • 3
  • 10
  • 1
    1) You can use ststic methods to access stuff without creating an instance of a class. 2) The variables in `doStuff` are local to the method, so it stays `null` outside. Look into Class variables or returning the `Thing` created. – AntonH Aug 15 '14 at 15:36
  • Java uses pass-by-value, the parameter variable will never be an **alias** of some variable passed. Rather an object (pointer) will be passed. – Joop Eggen Aug 15 '14 at 15:37

3 Answers3

3

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;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

This is because Java works by pass by value of Object references and not pass by reference of an Object ,even if the reference is an Object,it still gets passed by the value of reference.So you always work with new references

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
0

Refer:http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html

Declaring a Variable to Refer to an Object

Previously, you learned that to declare a variable, you write:

type name; This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable.

You can also declare a reference variable on its own line. For example:

Point originOne; If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code. Otherwise, you will get a compiler error.

A variable in this state, which currently references no object, can be illustrated as follows (the variable name, originOne, plus a reference pointing to nothing):

rupesh jain
  • 3,410
  • 1
  • 14
  • 22