Java’s Length Connundrum

Introduction

Arrays are one of the most common data structures in Java- and in programming as a whole, as are Strings. Strings are sometimes treated as primitives- even though they are just fundamentally char arrays with extra features. But that is a discussion for definitely a different time.

What you may have noticed is a weird discrepancy that pertains to Java having .length for arrays, and .length() for String objects.

This boils down to a side effect of object-oriented programming, but one that also is not necessarily an issue for other languages, as will be discussed later.

Why is String’s .length() a Method?

Yes, Strings are objects, but they actually inherit from the interface CharSequence. One property of an interface in Java is that it cannot contain fields. It only has the capability of defining abstract method definitions.

As a result, .length() has to be a method. The method .length() may be treated differently in the varying other inheriters of the class as well, so this makes sense. But did I know this even though I knew Java for 4 years? Nope. Fundamentally, you are almost never going to even use those different implementations in the first place. So in essence, this makes Oracle’s life easier- not yours. Sorry.

What About Arrays?

For arrays, the field length is made public, as well as final. The keyword public makes it accessible upon construction of the object (kind of a given there), but final on a side-note creates an important distinction. Final is a keyword that indicates an immutable (or unchanging state) once the object is intiailized. This makes sense, as once you initialize an array with a size or an array literal of elements, it will remain at a fixed size. As there is no interface inheritance here, interface, nor a reason to define length differently with arrays, it is a field with arrays- not a method.

public class ExampleDataStructure {
    public final int length;
    public ExampleDataStructure(int l) {
        length = l;
    }

    //Throws Error
    public void SetLength(int l) {
        length = l;
    }
}

A basic demonstration of why final is used in order to give arrays their fixed size upon initialization.

Other Languages?

At least as far as C# is concerned, it does allow for properties to be defined within interfaces. This is utilized within the interface implementations of data structures, for example:

public class ExampleDataStructure : ICollection {
    public int Count
    {
        get
        {
            return innerCol.Count;
        }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }
}