-2

when we use the length method for strings we use parenthesis, like:

String message = "Hello World";
System.out.println(message.length());

but when we use the same method with Arrays we don't use parenthesis

int [] numbers = {1,2,3,4,5};
System.out.println(numbers.length);

We use parenthesis with all other methods but not this one, why is that?

Faraz
  • 45
  • 1
  • 7

2 Answers2

2

It is not a method. It is a member variable. It can be accessed like this since it is public and final. Since it's final it can't be changed and thus invalidate the array. This goes back to the early beginnings of java.

0

Explanation

Why don't we use parenthesis () when calling the Array.length method in Java?

The reason is simple. It is not a method, it is just a public field.


Example

Pretty much as if you would write a class like this:

public class MyArray {
    public final int length;

    ...
}

and then something like

MyArray array = ...
System.out.println(array.length);

(this is a contrived example, but you get the idea)


Details

Note that arrays are implemented directly in the JVM and are not just simple classes like that. Same holds for length.

But those details do not matter much in practice, the syntax the language designers picked is the syntax of a regular public final int length field.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82