Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array doubt

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


at line 1, we assign an array with 3 elements to a empty array s declared with ZERO size, there is no compilation error, why is that?
 
Vidhya Ramaswamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An array is actually an object, and the arrayname is the reference.

s=arr; //-----------line 1

In this line, you are assigning the value of one reference to another, just as you would do for an object. So, the array size does not matter.

In effect, the array that 's' had earlier becomes unreachable and now, 's' and 'arr' point to the same location.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because array bounds aren't checked at compile-time. Like null pointers dereferences, this will compile fine but cause a runtime exception.

Why doesn't the compiler perform this check at compile-time? Probably because, from a computer science perspective, I suspect that it's not possible in general to determine statically whether an array out-of-bounds error will occur in a program, given that Java array sizes don't have to be compile-time constants.
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

at line 1, we assign an array with 3 elements to a empty array s declared with ZERO size, there is no compilation error, why is that?

In this case, its legal at compile time and runtime to assign one array to another, because simply you assign to the reference variable of the array Not the array its self.

But there is limitation, as the array you are assigning must be of the same dimension as the reference you are assigning to. For example:

At line 1, assigning 1D array to 1D array, hence valid statement.
At line 2, assigning 2D array to 1D array, Compile- time error.
[ November 04, 2007: Message edited by: Ahmed Yehia ]
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, I misread your question in my original response. Vidhya and Ahmed's responses above are correct. Essentially, the two key things to understand here are that:
  • the type of an array reference does not restrict it to a specific array length; and
  • the assignment statement in Line 1 does not copy elements from one array to another, but merely changes the array reference s to point to the array object arr.

  • [ November 04, 2007: Message edited by: Kelvin Lim ]
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic