1

Possible Duplicate:
In Java, for a string x, what is the runtime cost of s.length()? Is it O(1) or O(n)?

How exactly does the length method of String class work in Java ?

Is it a for loop in linear time or there is a field keeping the track of length so that its constant time ?

Community
  • 1
  • 1
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
  • 1
    Use [grepcode](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#658) to find out. You'll love it. (BTW that's a link I've posted :) – Marko Topolnik Jul 15 '12 at 11:58

4 Answers4

3

The length of a String is kept as a field as seen here : http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.length%28%29

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
1

There is a field to store the length. It doesn't need to "keep track of it" (with the implication that it might change) because strings are immutable.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

String stores its data in char[] array but there are cases when String should only use part of that array, that is why in its fields it stores beginning index (int offset) of that array, and length that should be used to generate String (int count). Method length() will return value of count field.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

A String is Immutable, so when a String object is created a its length is stored as an Instance variable for that String Object.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • That "so" implies more causality than there really is... You could have immutable strings without a length field, and a StringBuffer probably also has a length field, and it is not immutable. – Thilo Jul 15 '12 at 12:05
  • "so" is used in a context of reasoning here... – Kumar Vivek Mitra Jul 15 '12 at 12:06