Just to give more details to reply from @user28595.
Like the @Maniero noted in his comment, strings are immutable entities. In the other comments more links have been placed on the subject of immutability. One of the aspects that makes this immutability important is a matter of optimization: operations of substring
in Java can be implemented very lightly (source). Depending on the Java implementation, a substring can be implemented as a continuous set of information from a character array. From the example quoted in the source, in JDK6 "abcde".substring(1,3)
will generate a new object string, and it carries the same array of characters {'a', 'b', 'c', 'd', 'e'}
of string initial, but he considers that he starts from the position 1
(b
) and goes right before the position 3
, so it would be the position 2
(c
). Not always a Java implementation ensures that a string has the size of the character array that loads your data, it may be that you only load part of it. If this is the case with string store the start and end index, the method length()
returns fim - comeco
; if implemented with offset
of the first character and count
, then the result of the method would be count
(as the example he gave of how it was in JDK6). If the implementation of string make a copy of the subvector desired is used (as the example informs you do in JDK7), so the method length()
simply returns vetorDeChar.length
.
An advantage of implementing the string.length()
as a method one can completely change the internal implementation (including existing fields) without the programmer using a string is affected. For smaller applications, the strategies of implementing string are not initially felt.
@Maniero talks about encapsulation access properties that could solve this Java idiosyncrasy
An interesting point about vectors is that access to their size is optimized by JVM. There is a bytecode specialized in doing this: 0xBE
, identified by the mnemonic arraylength
. Use that bytecode has a generated result less than what would be generated if the bytecode traditional of picking up fields, the getfield
(0xB4
), which requires two additional bytes for the attribute index. A Wikipedia has a page listing bytecodes.
array != String.
length
is a final variable and publishes arrays, which return the size defined by you then start the array. Already the methodlength()
returns how many characters are in a String.– user28595
length
in an array is a previously known attribute, while in a string this can be changed to for the sake of memory optimization in substrings, thus not holding its value to the actual size of the information container– Jefferson Quesado