Results 1 to 3 of 3
  1. #1
    castiel is offline Member
    Join Date
    Aug 2009
    Posts
    26
    Rep Power
    0

    Default 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.
    Java Code:
    Integer val1 = new Integer(10);
    Integer val2 = val1;
    val2++;
    System.out.println(val1);
    Expected Value of val1: 11
    Actual Value of val1: 10

    This referencing works for my own objects
    Java Code:
    Point p1 = new Point(5,10);
    Point p2 = p1;
    p2.x = 1000;
    System.out.println(p1.x);
    Expected Value of p1.x = 1000
    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

  2. #2
    revathi17 is offline Member
    Join Date
    Aug 2007
    Posts
    26
    Rep Power
    0

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,792
    Rep Power
    19

    Default

    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:
    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);
        }
    results in true then false.

Similar Threads

  1. Reference variable
    By lala in forum New To Java
    Replies: 2
    Last Post: 02-03-2011, 07:27 PM
  2. how to get reference from outside class
    By kiruba in forum New To Java
    Replies: 5
    Last Post: 01-07-2011, 07:17 AM
  3. Object and reference
    By katie in forum New To Java
    Replies: 2
    Last Post: 10-19-2009, 03:45 PM
  4. removing reference
    By ajith_raj in forum Advanced Java
    Replies: 4
    Last Post: 02-12-2009, 11:46 AM
  5. Getting the Object Reference Name
    By Deathmonger in forum New To Java
    Replies: 2
    Last Post: 03-12-2008, 02:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •