• Post Reply Bookmark Topic Watch Topic
  • New Topic

Assigning different arrays to one another  RSS feed

 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI guys, I run into something interesting. This snippet of code (compiled and tested) works:



This print first 10 and 11 and then after the assignment of myString2 to myStrings 11 and 11. Why is this possible? I would have expected an exception, probably index out of bound or something like that?
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The assignment on line 5 sets both variables to point to the same array.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While the way you did it is syntactically legal, the normal way to declare arrays is to put the brackets after the type, like so:

Variables declared like that are references so when you assigned myStrings2 to myStrings, you simply changed which array myString referenced, you didn't change the array itself. So, the 10-element String array that myString was referencing is basically thrown away and you end up with both variables referencing the same 11-element array after the assignment.
 
praveen kumaar
Ranch Hand
Posts: 461
22
Android Chrome Eclipse IDE Google App Engine Java Notepad Oracle Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because before line 5(assigning mystrings to mystring2),the 2 array references(mystrings and myString2) are pointing the 2 different array objects(array of String object) of size 10 and 11 respectively.at line 5 you made a myStrings to point the same Array object referenced by myStrings2 which has a size 11.
please read about the topic-Java is Pass By Value(Copy).There you will have more grasp about what actually it meants to assign a reference to other reference.

Kind Regards,
Praveen.
 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Understood, thanks guys!
 
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!