• Post Reply Bookmark Topic Watch Topic
  • New Topic

reference in an array  RSS feed

 
amal shah
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
i am faced with the following problem:

i have a String array as:
String s="Small";
String array[]={s,"Large"};

now at runtime i change String s as s="Medium";
and then i print array[0];i should get output as "Medium" but am getting "Small"....i am not able to get it.....

help appreciated
cheers
amal shah
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because these are REFERENCES to objects.

you have the objects, the Strings, that live in the heap. this includes "Small", "Large", and "Medium".

you have the REFERENCES 's', array[0], and array[1]. These are like notecards with an address written on it.

so,

writes the address of "Small" on the notecard/assigns the address to 's'.

says "I need two more notecards to put addresses on, and stuff them in the array.". Then, the address written on s is COPIED to array[0], and the address of "Large" is written on/to array[1].

Now, when you do you erase what was written on that card, and put a new address on it. This in NO WAY effects what is written on any other card. The array[0] reference still points to where it always had, that is the "Small" String.
[ April 27, 2007: Message edited by: Fred Rosenberger ]
 
amal shah
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks fred.....that helped......
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!