0

I'm a c++ programmer, and I'm currently learning Java, and when trying to understand how Java works I wondered... if I save an object from a data structure such ArrayList in a variable, and then erase that object, will that object still be there? Since assigning an object to a variable stores the pointer to that object, once it's erased, will it be a null object or will that be a copy of the erased object?

For example

ArrayList list = new ArrayList<Object>();
Object object = list.getObject(...)
list.remove(...)

Will object be null?

Would this change the behaviour?

ArrayList list = new ArrayList<Object>();
Object object = new Object();
object = list.getObject(...)
list.remove(...)
magalenyo
  • 275
  • 6
  • 17
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – SomeJavaGuy Apr 20 '17 at 14:08
  • java doesn´t have pointers, everything is passed as values, references aswell, just that in this case it´s the value of the reference. As though yes, the object will still be there, as you´re just changing the value of the reference for the variable but don´t stand a change to change the actuall reference itself – SomeJavaGuy Apr 20 '17 at 14:10
  • As a C/C++ developer I find this interpretation easier (YMMV): There are only pointers in Java (except primitive types) and since there are no non-pointers, the `*` is omitted. With `Object object = new Object();` you have a pointer to the `Object` instance. With another `Object object2 = new Object();` you can compare `object == object2` and actually compare the pointers to the instances. You can set `object = null;` and if you call methods on `object` you even get a `NullPointerException` :-) Apart from that, usually variables don't become `null` (search for "weak" for cases when they do). – Rainer Schwarze Apr 20 '17 at 15:02

0 Answers0