wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes basic question about array ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "basic question about array ?" Watch "basic question about array ?" New topic
Author

basic question about array ?

mark stone
Ranch Hand

Joined: Dec 18, 2001
Posts: 417
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

Joined: Jan 13, 2002
Posts: 732
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

Joined: Aug 26, 2001
Posts: 7610
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


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
mark stone
Ranch Hand

Joined: Dec 18, 2001
Posts: 417
thanks roy and valentin.
i have posted a different question but this time on primitive values.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: basic question about array ?
 
Similar Threads
Multi Dimension Array Storing
multidimensional array doubt
Can't Perform Same Search Twice
Transfer from C /C ++ ( URGENT)
String array problem