• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

primitive arrays and their length

 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just wondering what gives an array of primitive type its "length" property?
i.e. when I have -
int[] arr = new int[10];
How is the call arr.length resolved by the compiler, as type of array here is int[]?
TIA,
- Manish
p.s. I hope I am not flooding the forum with silly questions.
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are objects in Java and length is a public final property of arrays.
More info at :JLS 10 Arrays
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Manish the compiler uses a special bytecode to get the length of an array objetc: arraylength.
Though the length of an array is a field of the array object, compiler doesn't use the normal getfield or getstatic bytecodes:

public class Tux extends Thread{
Tux() {
System.out.println(new int[9].length);
}
}
javap -c Tux
Method Tux()
0 aload_0
1 invokespecial #1 <Method java.lang.Thread()>
4 getstatic #2 <Field java.io.PrintStream out>
7 bipush 9
9 newarray int
11 arraylength
12 invokevirtual #3 <Method void println(int)>
15 return
 
Manish Hatwalne
Ranch Hand
Posts: 2595
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Valentin and Jose
Jose, any specific reason for extending Tux from Thread?
- Manish
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not at all. Just a piece of code from a previous program. Sorry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic