Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java calculate length of primitive array? [duplicate]

Code:

char[] chars = "abcd".toCharArray();
System.out.println(chars.length);

Question: How is length calculate by Java here? Since char is not a Class, I am not sure where length is stored. If it isn't stored, is it calculated every time you do chars.length? (I presume not)

like image 454
Farhan Syed Avatar asked Oct 21 '25 12:10

Farhan Syed


2 Answers

The thing you wrote as char[] is an Object, an array, and has a public final field called length. It is calculated once when the array in created. Like all objects it also has a toString(), notify(), etc...

like image 86
user949300 Avatar answered Oct 23 '25 02:10

user949300


http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7

The public final field length, which contains the number of components of the array. length may be positive or zero.

like image 43
dbf Avatar answered Oct 23 '25 02:10

dbf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!