Search code examples
javaarraysstringstring-length

how does 'length' work to return the length of a String type array object in Java?


we have length()- a method that returns the length of a String object,

for example:

 String s, sarr[] = {"a","b"};  
 System.out.println(s.length());  
 System.out.println(sarr.length);

in Java. But what does happen, in background, in case of String type array object that we have to use length , probably a parameter, that returns the length of that said array object?


Solution

  • Every array in Java has a field length. On the other hand, String has private final char value[]; field which has it's length.

    Method length() of String returns the length of the value.

    The length of value is final so there is no danger of public field being vandalized.