length property:
The length variable is used to return the size of an array, i.e. number of elements stored in an array.
public class Hello{
public static void main(String args[]) {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
System.out.println("Length of an array is: " + arr.length);
}
}
Output:
Length of an array is: 7
If round brackets come after a Java length property, the following code error occurs:
Cannot invoke length() on the array type int[]
length() method:
The length() method returns the length of a string object i.e. the number of characters stored in an object.
public class Hello {
public static void main(String args[]) {
String str = "Welcome";
System.out.println("Length of String using length() method is: " + str.length());
}
}
Output:
Length of String using length() method is: 7
If round brackets do not follow a Java length() method call, the following code error occurs:
length cannot be resolved or is not a field
Key differences between length and length()
length property | length() method |
used with the array class | used with the String class |
returns the size of an array | returns the number of characters in a string |
throws a compile error if you add round brackets | length method must have round brackets at the end |
has its roots from C and C++ programming | is a good example of data encapsulation |