Y
3 months ago
Yichaocountry asked

In Java, why do arrays use length and not length()?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hi Yichao,

In Java, length for an array is a field (a value stored in the array), not a method. That is why you write it without parentheses:

int[] nums = {1, 2, 3};
System.out.println(nums.length);  // 3

Parentheses are only used for methods. For example, strings use a method:

String s = "abc";
System.out.println(s.length());  // 3

So the simple rule is: arrays use length, strings use length().

If you have more questions, I am here to help 😊

Java
This question was asked as part of the Learn Java Basics course.