File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

basic question about array ?

 
mark stone
Ranch Hand
Posts: 417
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
following code snippet compiles and runs fine.
But is the assignment a = k; fine ?
i do not think so. But apparantly it is indeed fine. BUT WHY ?
we defined array a as of one element.
and then how come it does not complain when it is assigned now two elements. Can arrays grow in size ???
int a[] = {1};
int k[] = {5,6};
a=k;
System.out.println(a[0]);===> prints 5
i am stuck at this point.
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a is not the array itself.
you need to understand that a is a refrence that can point to array objects.
in this case u tell the refrence to point first to an array of 1 member with one.
thats ok.
than u take that reference and u tell it to point to where refernce k points (refers) to which is another array object with 2 memebers ( 5 and 6).
now the first array object will get garbaged collected later or sooner cause there are no more refrences to it.
the other array object has 2 refernces to it ( a and k ) and u can use either one to change or show that array.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See it that way:
int a[] = {1};
declares and initializes an array of ints.
a points to the location in memory where the elements of the array a are, i.e.
a--->1
int k[] = {5,6};
declares and initializes an array on ints.
k points to the location in memory where the
elements of the array k are, i.e.
k--->5--->6
a=k;
makes the pointer to array a point to the array k, now a and k are both pointing to the same array i.e. the one initially pointed to by k. The elements pointed to by a are now unreferenced and lost (they will be garbage collected.)
HIH
 
mark stone
Ranch Hand
Posts: 417
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks roy and valentin.
i have posted a different question but this time on primitive values.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic