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


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "array" Watch "array" New topic
Author

array

sweety sinha
Ranch Hand

Joined: Jul 07, 2008
Posts: 76
class checkarr{
public static void main(String []args)
{
int [] arr = { 1 ,2 ,3 ,4 ,5};
System.out.println(arr.length);
int [] arr2 = new int[4];
System.out.println(arr2.length);
arr2 = arr;
System.out.println(arr2[4]);
}
}
why it is compiling without problem?
arr has length 5 and arr2 has length 4, even then arr2 = arr is possible(how?). and arr2[4] is giving output, but as we know that its length is 4 so we can get output till arr[3].
M Srilatha
Ranch Hand

Joined: Aug 27, 2008
Posts: 137
The code compiles properly as everything is correct.
when you assign arr to arr2 variable, arr2 and arr points to the same array that is created in the first line in the main.
so arr2[4] works as the array that arr2 points to is of length 5.
And the array created at line 3 is lost as there is no reference variable pointing to that.


I hope you get it!


Thanks,<br />Srilatha M
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9307
    
  17

when you create the two arrays the memory representation for the two arrays looks like this

you can see that arr and arr2 represent two different arrays
after arr2 = arr is executed, then the memory representation for the two arrays looks like this

So as it is clear, that after arr2 = arr is executed, then both arr and arr2 refer to the same array which has the length 5. This is why you can refer to the element arr2[4]...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Akhilesh Trivedi
Ranch Hand

Joined: Jun 22, 2005
Posts: 1527
Arrays in java are treated as objects. Both arr and arr4 are references.


Keep Smiling Always — My life is smoother when running silent. -paul
[FAQs] [Certification Guides] [The Linux Documentation Project]
sweety sinha
Ranch Hand

Joined: Jul 07, 2008
Posts: 76
thanks all

Ankit your graphical presentation is very good
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9307
    
  17

Mayur Somani
Greenhorn

Joined: Apr 14, 2008
Posts: 26
Oh My!
 
jQuery in Action, 2nd edition
 
subject: array