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.
Java
import java.io.*; class GFG { public static void main(String[] args) { int arr[] = new int [ 3 ]; int size = arr.length(); } } |
Try to run the above code. You will see that there is a compile-time error due to the usage of length().
Compile Error:
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.
Java
// Java program to explain // length field in array object public class Main { public static void main(String args[]) { // arr is an integer array int [] arr = new int [ 3 ]; // length is a field variable for array arr System.out.println( "Length of the array is: " + arr.length); // str in a String String str = "GeeksFor" ; // length() is method for // getting length of string System.out.println( "Length of the string " + str + " is: " + str.length()); // Updating the string str += "Geeks" ; System.out.println( "Length of the updated string " + str + " is: " + str.length()); } } |
Length of the array is: 3 Length of the string GeeksFor is: 8 Length of the updated string GeeksForGeeks is: 13
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been used.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!