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

how to run arquillian test with gradle in intellij,how to set the build.gradle file?
Oracle date conversion error ORA-01858
Java Static method used as Oracle function
How to change the button upon click ,and revert back to normal upon release the button?
Refreshing Caches while under load with Spring/EHCache
Do you do input parameter validation in Resource class or Service Class?
java.lang.ClassCastException when using java 8 but things are fine with java 7
Run Ant script from Gradle
Running a new network request inside onPostExecute
How can I disallow to use my own annotation for all classes instead of classes implementing concrete interface
java8 streams and state
Opening and appending files
Java MouseListener MouseClicked only works once
Multiple swt buttons, same listener [duplicate]
Troubles creating an index with custom analyzer using Jest
Is there a way to inverse/inverse an ImmutableMap

Categories

HOME
ibm-bluemix
xamarin
log4j
pdf
openstack
magnific-popup
single-sign-on
pycharm
spagobi
read-eval-print-loop
getelementsbytagname
leon
ezpublish
constraint-programming
webrequest
virtualization
elasticsearch-hadoop
volttron
mapserver
evopdf
lldb
css-animations
excel-2007
language-agnostic
wijmo
phpfox
windowbuilder
gsoap
flink-streaming
nameservers
gammu
dosbox
bitbucket-pipelines
scaffold
hot-module-replacement
jna
graphenedb
dism
android-mediaprojection
angular2-meteor
galleria
angular-resource
user-accounts
filepicker
pango
react-scripts
multipeer-connectivity
python-webbrowser
setter
spring-cache
quartz-composer
background-service
eventkit
wdf
angular-cache
phishing
qpid
clang-static-analyzer
blackberry-10
yaws
php-parse-error
ios4
independentsoft
pyke
xna-4.0
intel-fortran
jmeter-maven-plugin
qdialog
cakephp-3.1
event-bubbling
fluid-dynamics
generic-programming
iiviewdeckcontroller
graph-api-explorer
inmobi
rake-task
typekit
jsonpickle
gadt
tt-news
applescript-objc
preferences
zend-route
fluentautomation
transcoding
ember-charts
c18
commoncrypto
google-cloud-save
gridcontrol
seed
limejs
eventlistener
tinn-r
ticoredatasync
spring-portlet-mvc
punbb
netdna-api
gnu-prolog
libc++
vdsp
yui-datatable
imac
mongomapper
lpeg
asp.net-mvc-areas
exchange-server-2003
ctp4
swing-app-framework
pascal-fc

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