aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes primitive arrays and their length Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "primitive arrays and their length" Watch "primitive arrays and their length" New topic
Author

primitive arrays and their length

Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2579

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

Joined: Aug 26, 2001
Posts: 7610
Arrays are objects in Java and length is a public final property of arrays.
More info at :JLS 10 Arrays


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

Joined: Jul 03, 2001
Posts: 2120
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


SCJP2. Please Indent your code using UBB Code
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2579

Thanks Valentin and Jose
Jose, any specific reason for extending Tux from Thread?
- Manish
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Not at all. Just a piece of code from a previous program. Sorry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: primitive arrays and their length