Why in Java is the size of an array an attribute and a String and a method?

Asked

Viewed 2,425 times

11

In Java, the size of a array of any object can be obtained with length, which would be an attribute. But in the case of String is length(), a method. However, if you have a array of String, uses length, an attribute. Why?

For example:

    int[] a = {1,2};
    String b = "str";
    String[] c = {"aa", "bb"};

    a.length;
    b.length();
    c.length;
  • 1

    array != String. length is a final variable and publishes arrays, which return the size defined by you then start the array. Already the method length() returns how many characters are in a String.

  • 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

3 answers

14

I researched because I wanted to know the reason. I concluded that there are only speculations, nobody knows the real reason. Only the developers can answer this.

What seems clear to me is that the fact of array being a language construct would be more appropriate to have a property than a ghost method that language treats. Moreover, as this was one of the first things created in language perhaps they did not think that a method could be better and more consistent.

String is a common class and Java does not have properties that only encapsulate access methods, that is, it could only have the field exposed if it did not use a method. It would create compatibility problems between implementations, versions and would even be inconsistent with other structures that need the method, a case is the CharSequence. It’s not really necessary since String is immutable, its value is not to change.

There are other theories, including those listed here, but they do not seem to make sense to me because even a public field could be placed its value whenever necessary. Perhaps they realized that there would be a new attribute occupying space that might or might not be necessary.

I’m not a fan of the term attribute that is even used in language. It uses field for this.

11


Arrays are treated differently from Strings, ArrayLists or anything else that can be counted in Java. A Array is practically a native type and its length cannot be changed after it is initialized, so there is no need for encapsulation. The length variable can be directly exposed without side effects.

The reason why Strings uses a method instead of a variable is because it internally uses a char[]who does not wish to expose publicly (for reasons of immutability/encapsulation), so involves the length variable in a method length(). It’s the same reason ArrayList have a method size() instead of a variable length.

Translated from What’s the Difference between length and length()?

Just remembering that a String itself is also immutable, and not only the array of char used internally by it, as can be confirmed in class documentation

  • 2

    String tb is immutable. Actually even more than the array. The real reason is Gambi :) And C# made the same mistake. Well, there is even a half semantic reason in the use of the same word. A curiosity is the difference between size, length and Count

  • @unchangeable bigown serves to ensure that no other processing ends with a previously expected dataset

  • @Jeffersonquesado can read about it at https://answall.com/q/15510/101.

  • @bigown added this information to the answer, to avoid misunderstandings with this class.

  • @Bigown, I’ve been browsing through the question you sent me and I found this here, also relevant: https://answall.com/q/103460/64969

  • 2

    @Jeffersonquesado pena que tudo o que é resposta mais recentemente dá menos Bope, this talk of some important things.

Show 1 more comment

7

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.