4

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)

Farhan Syed
  • 336
  • 3
  • 15

4 Answers4

8

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...

yshavit
  • 42,327
  • 7
  • 87
  • 124
user949300
  • 15,364
  • 7
  • 35
  • 66
3

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.

dbf
  • 6,399
  • 2
  • 38
  • 65
0

In this case chars.length is returning the number of elements in the array.

Or am I missing the question?

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Even though char is not a Class/Object type in Java, an array of char actually is. And the length is a (final) field of that class. See the answer here for more.

Community
  • 1
  • 1
Turix
  • 4,470
  • 2
  • 19
  • 27