java


Pointers and objects in java


let's consider the following code:
public class Test {
private int a;
public Test(){
this.a = 1;
}
public static void main(String[] args) {
Test A = new Test();
Test B = A;
// TEST1
B.a = 0;
System.out.println(A); // prints 0
// TEST2
B = null;
System.out.println(A); // also prints 0
}
public String toString(){
return Integer.toString(this.a);
}
}
In TEST1, we modify B and then A is modified because B points to A.
I may understand why in TEST2 A doesn't become null, because B now points to null.
But the results of the two tests seem contradictory: why A doesn't become null ?
Thanks.
Test A = new Test();
The variable A points to an instance of type Test
Test B = A;
The variable B points to the same instance as variable A does.
B.a = 0;
The instance, variable B is pointing to (the same instance variable A points to), is changed.
B = null;
Variable B does not point to any instance anymore, while variable A still points to the same instance of type Test as before.
The main thing to understand is that variables A and B do hold a pointer to an instance of type Test. The instance of type Test is represented somewhere in memory and many variables may reference (point) to it.
The expression:
B.a = 0;
means: find the instance B is pointing at and modify its state in memory.
The expression:
B = null;
means: let B point to some other instance in memory (in your case to no instance at all). While the expression:
B = A;
means: let B point to the same instance in memory as A does point to.
The variables A and B were both referencing the same object. B.a = 0 is altering that object. But when you reassign B = null, you're not altering the object. You're just altering the variable.
By making object b null, you just cut the referance between the test object which resides in the heap and the B. The other referance between the test object and the A remains regardless of the other referances of the object unless you cut it or changed it.
regards
In Java variables are stored in the stack, while objects themselves are stored in the heap. Primitive type values are also stored in the stack, thus primitive type variables don't touch heap at all. But object variables on the stack contain heap addresses instead of values themselves. So by assigning null to B you change the B's (and only B's) value on the stack, but the heap value remains unchanged, and A's value on the stack remains unchanged, so A still references the same object in the heap allowing you to access its attributes and methods.

Related Links

Use of str.length()-1 in case of swapping a letter of a word with each other [closed]
what will cause socket write throws connection timeout exception
Apache POI get line breaks from XWPFRun
Android Display 2 fragments inside another one
Dynamic addition of column in TableView and editing cells using javafx
Java Reflection : invoking inherited methods from child class
If Else Condition not Working in Increase and Decrease Value of qty
For each save (update) hibernate envers creating revisions either changed in table or not
Starting Tomcat with CMD
org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)
Assert 2 Lists<String> are equal ignoring order
NoSuchMethodException SoapUI Java
Why can this object access methods of it's parent class?
SQLite database already created and in Android Studio but how do I display information from the database in my application? [duplicate]
Avoid displaying Java Object with description in swagger ui
handling enter key press in editText [duplicate]

Categories

HOME
pdf
bluetooth
hive
wso2
blogger
youtube-dl
framework7
umd
uber-api
swagger-ui
handsontable
resize
flask-wtforms
try-catch
workload-scheduler
opentracing
highlight.js
google-static-maps
reactcsstransitiongroup
pythonanywhere
samoa
textfield
nodatime
amazonsellercentral
autocad-plugin
scriptcs
errorlevel
language-agnostic
sparse-matrix
pepper
su
bootstrap-material-design
rst2pdf
elasticsearch-ruby
elasticsearch-net
tasklet
librato
stormpath
directx-10
javascriptcore
create-table
fog
azure-sql-database
sequential
http-digest
revolution-slider
android-browser
webdriver-manager
squib
gzipstream
elmah
jvm-languages
no-www
outlook-api
apple-news
taffy
fault
dotnetzip
lowpass-filter
setter
nativeapplication
cudafy.net
sqldf
mediaelement
quartz-composer
migradoc
angular-strap
ableton-live
passport-google-oauth
transmitfile
google-web-starter-kit
websitepanel
jwplayer7
bluemix-app-scan
rtbkit
srand
ora-00900
endeca-workbench
atk4
microbenchmark
event-bubbling
census
sorl-thumbnail
clicktag
xc16
angularjs-ng-click
java.util.concurrent
android-imagebutton
cctv
aapt
hippomocks
ember-charts
srs
back-stack
nsmanagedobject
semantic-diff
assembly-loading
pydot
tomcat-valve
krl
site.master
h.323
zend-translate
jquery-ui-droppable
forums
bespin
iweb
javap
privilege

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App