• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array

 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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]...
 
Akhilesh Trivedi
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays in java are treated as objects. Both arr and arr4 are references.
 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks all

Ankit your graphical presentation is very good
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Mayur Somani
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh My!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic