Results 1 to 3 of 3
Thread: Reference assignment query?
- 03-07-2011, 04:40 AM #1
Member
- Join Date
- Aug 2009
- Posts
- 26
- Rep Power
- 0
Reference assignment query?
I was wondering why this doesn't work. I thought when I said
val2 = val1 that I was saying that val2 points to the same memory address
as val1 and so my modifying the value of val2 I am also modifying the value of
val1 but I've noticed for Integer and String that the values are not equal when modified.
E.g.
Expected Value of val1: 11Java Code:Integer val1 = new Integer(10); Integer val2 = val1; val2++; System.out.println(val1);
Actual Value of val1: 10
This referencing works for my own objects
Expected Value of p1.x = 1000Java Code:Point p1 = new Point(5,10); Point p2 = p1; p2.x = 1000; System.out.println(p1.x);
Actual Value of p1.x = 1000
Can someone please tell me what's so special about Integer and String and why they behave differently? If there's any good explanation about this on the web I would be happy to read.
Cheers
- 03-07-2011, 06:16 AM #2
Member
- Join Date
- Aug 2007
- Posts
- 26
- Rep Power
- 0
- 03-07-2011, 11:26 AM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,484
- Rep Power
- 16
Primitive wrapper objects like Integer are immutable. That is, you cannot change the data in them after creation. String is the same.
As revathi17 has shown, what you see for Integer is a side effect of auto-boxing. The call to '++' results in a dereference of val2 to an int, then it is incremented, then that int is rewrapped into a new Integer. So val2 is no longer '==' val1.
The following:
results in true then false.Java Code:public static void main(String[] args) throws Exception { Integer val1 = 10; Integer val2 = val1; System.out.println(val1 == val2); val2++; System.out.println(val1 == val2); }
Similar Threads
-
Reference variable
By lala in forum New To JavaReplies: 2Last Post: 02-03-2011, 07:27 PM -
how to get reference from outside class
By kiruba in forum New To JavaReplies: 5Last Post: 01-07-2011, 07:17 AM -
Object and reference
By katie in forum New To JavaReplies: 2Last Post: 10-19-2009, 03:45 PM -
removing reference
By ajith_raj in forum Advanced JavaReplies: 4Last Post: 02-12-2009, 11:46 AM -
Getting the Object Reference Name
By Deathmonger in forum New To JavaReplies: 2Last Post: 03-12-2008, 02:51 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks