How does Java get the length of arrays and strings? Length or length()?”

I came across this theme while browsing programcreek. To be honest, I had this terrifying image in my mind:

The interviewer, Lao Ma, sat across from me and I admired his Mediterranean hairstyle. He confidently posed the above question to me, though a little tired. After some hesitation, I replied, “Use length for arrays and length for strings followed by parentheses.” Lao Ma is worthy of being a master in the interview, and captured the unconfidence from my answer in an instant. I could tell because I saw the corners of his mouth move slightly, as if he wanted to smack them. But out of courtesy to me, he refrained.

Whether to use length or length(), to be honest, I was a little unsure at the time, I missed the IDE code automatic reminder function ah!

int[] arr = new int[4];

System.out.println(arr.length);// Get the length of the array



String str = "Silent King II.";

System.out.println(str.length());// Get the length of the string

Copy the code

In theory, arrays and strings are objects, and the length() method should be used. Why is the array chosen to use the length field?

First of all, we must understand that an array is a container, and when it is created, not only the type of the elements is determined, but also the number of elements is determined. In other words, the length of the array is fixed, and it can’t get longer or shorter. Therefore, arrays can use a single field (Length) to indicate their length.

There are two ways to create an array, which you probably already know. One is to create the specified length with the new keyword and then assign it, and the other is to initialize it directly with {}.

// new

int[] arr = new int[4];

arr[0] = 0;

arr[1] = 1;

arr[2] = 2;

arr[3] = 3;



/ / {}

int [] arr1 = {0.1.2.3};

Copy the code

But either way, the length of the array is clearly known. And it will not be longer or shorter (can not learn sun Wukong’s golden stick).

Since arrays are also objects, the following code is legal.

Object arr2 = new int[4];

Copy the code

This means that the array inherits all the member methods and fields of the superclass java.lang.Object. In fact, it does, and we can get the array’s type information Class with the following code.

Object arr2 = new int[4];

System.out.println(arr2.getClass());



Object arr3 = new String[4];

System.out.println(arr3.getClass());

Copy the code

What would the output be?

class [I

class [Ljava.lang.String;

Copy the code

Class [I represents the object type information of an “int array” at runtime; class [ljava.lang.string; represents the object type information of a “String array” at runtime.

So why not define a separate class for arrays? Like the String class?

One plausible explanation is that Java hides it. If there is an array.java, as we can imagine, it must define a container to hold the elements of an Array, just like the String class.

public final class String

    implements java.io.Serializable.Comparable<String>, CharSequence 
{

    /** The value is used for character storage. */

    private final char value[];

}

Copy the code

But is this really necessary? To define a single class for arrays is to gild the lily. There is no need to define a length() method to get the length of the array. We can just use length, right?

So why does the String class have a length() method? Take a look at the source code to understand.

    / * *

     * Returns the length of this string.

     * The length is equal to the number of Unicode

     * code units in the string.

* /


    public int length(a) {

        return value.length;

    }

Copy the code

The length() method returns exactly the length of the character array value. Value itself is private, so it makes sense to provide the String class with a public-level method for external access to the length of the character.

To summarize, Java uses length to get the length of an array and length() to get the length of a string. I’m sure you’ve figured out the difference.

One final note: Great oaks from little acorns grow. How high a building can be built, how long a bridge can be built, the important thing is their foundation. Similarly, for our technical personnel, the more solid the basic knowledge, the farther we will go.


Well, readers, that’s all for this article. Can see here is the most excellent programmers, two elder brother must extend a lovely thumb for you a thumbs-up 👍. If you don’t like it and want to see more, I recommend a few more.

Soul Searching: Why Are Java Strings immutable?

Soul torture: Create Java strings with “” or constructor

Soul check: How do I check if a Java array contains a value?

Soul Searchers: How does Java substring() work?

Develop good habits! If you are a loyal reader of the second brother, please don’t be stingy with your left mouse button, just click “like”, next year’s promotion and salary is yours! If you want to see the second brother’s original article for the first time, scan the following code on the right.