Java is pass by value, and you pass the reference to an object, not the object itself. I think it is very important to know this since this will let you understand how Java works much much better, so let's go step by step on your code and see why it doesn't work the way you expect.
Object obj = null;
someMethod(obj);
void someMethod(Object obj) {
Here, obj
reference is copied (not the object instance, only the reference to it) then passed to someMethod
.
obj = new Object();
Here you're overwriting obj
value but only in the scope of the method. Note that obj
reference in the caller (outside someMethod
) has not changed, because it is a copy. After the method finishes, obj
reference in this scope is discarded because we go out of scope, and you go back to the caller scope. In this scope, obj
is still null
. Thus
System.out.println(obj.getId());
obviously throws NullPointerException
.
If you want to get the new reference from the method, you can return it and assign it in the caller scope, for example:
Object someMethod() {
obj = new Object();
// Do stuff with obj
return obj;
}
Object obj = someMethod();