Why Array.length() gives error when used in Java?
What will happen if we use Array.length()?
Before moving to the reason why we cannot write Array.length(), let us first see what will happen if we try to use the Array.length() in the Java code. Below is a code snippet to check that.
Try to run the above code. You will see that there is a compile-time error due to the usage of length().
Main.java:6: error: cannot find symbol int size = arr.length(); ^ symbol: method length() location: variable arr of type int 1 error
Why cannot we use Array.length() in Java?
We have seen that using length() gives an error. But the question is why?
Though arrays are objects in Java but length is an instance variable (data item) in the array object and not a method. So, we cannot use the length() method to know the array length.
Once the length variable of the array is initialized, it cannot be modified or changed. It is used only for arrays and gives the size (length) of the array i.e., the total number of elements in the array.
Whereas String objects in Java have the length() method, this method returns the number of characters present in the string at that time. This method is a way to access the field member of the object. It is modifiable with the operations performed on the string.
length field is used in arrays like: int, double, long, String, etc.
length() method is used in String objects like: String, StringBuilder, etc.
Implementation of length instance variable and length() method:
The below code snippet showcases the use cases of length instance variable and length() method.
Length of the array is: 3 Length of the string GeeksFor is: 8 Length of the updated string GeeksForGeeks is: 13