Java: why doesn't Array.length have (), but String.length () does?

Why, when we get the length of the array, we do not need to place () as

int [] ar;
System.out.println(ar.length); // no parentheses 

but for the string it will be

String st;
System.out.println(st.length());
+4
source share
4 answers

why does Array.length have no () but String.length () does?

At the syntactic level, it really comes down to "historical reasons" and "because the Java (pre) 1.0 developers decided to do this." The only people who can really tell you why the language developers themselves are.

However:

  • The field lengthis special in the sense that it is actually located in the header of the array object, and the selection of the length of the array uses a special byte code.

  • length , . , , .. ( final .)

length .


(pre-) Java API- .

, . length() size() , .., Java . ( Java), .

+6

:

  • length - ! length 10, 2 .
  • , (A String - Object, ), . , . , length() !

, - . , - ( ), JVM, , -.

(Array -Class - .)


, Array ( a) - array.length . ( , - ( C, realloc) , array.length * elementSize.

, , . ( , size(), , .)

+2

( ) ( , ).

. . , , , , String :

  • String CharSequence, length(), String . ( , .) , .

  • . : char , char. , char ( ) . , , String char , length . String , , , API , .

+1

Array lengthis an int int, but String (and other objects) usually use the getter method.

Note that the difference in two is that the string “length” is simply the amount of information that it already stores in the internal array char, but the field of the array lengthis simply its capacity.

0
source

Source: https://habr.com/ru/post/1547083/


All Articles