- array.length: length is a final variable applicable for arrays. With the help of length variable, we will obtain the dimensions of the array.
- string.length(): length() method is a final variable which is applicable for string objects. length() method returns the amount of characters presents within the string.
length vs length()
The length variable is applicable to array but not for string objects whereas the length () method is applicable for string objects but not for arrays.
Examples:
// length can be used for int[], double[], String[]
// to know the length of the arrays.
// length() can be used for String, StringBuilder, etc
// String class related Objects to know the length of the String
To directly accesses a field member of array we will use .length; whereas .length() invokes a way to access a field member.
Example:
// Java program to illustrate the
// concept of length
// and length()
public class Test {
public static void main(String[] args)
{
// Here array is the array name of int type
int[] array = new int[4];
System.out.println("The size of the array is " + array.length);
// Here str is a string object
String str = "wikitechy";
System.out.println("The size of the String is " + str.length());
}
}
Output
The size of the array is 4
The size of the String is 9
Let’s have a look on the output of the following programs?
1.What will be the output of following program?
public class Test {
public static void main(String[] args)
{
// Here str is the array name of String type.
String[] str = { "wikitechy", "kaashiv" };
System.out.println(str.length);
}
}
Output
Explanation: Here the str is an array of type string and that’s why str.length is used to find its length.
2.What will be the output of following program?
public class Test {
public static void main(String[] args)
{
String[] str = { "wikitechy", “kaashiv” };
System.out.println(str[0].length);
}
}
Output
error: cannot find symbol
symbol: method length()
location: variable str of type String[]
Explanation: Here the str is an array of type string and that’s why str.length() can’t be wont to find its length.
3.What will be the output of following program?
public class Test {
public static void main(String[] args)
{
String[] str = { "wikitechy", “kaashiv” };
System.out.println(str[0].length());
}
}
Output
Explanation: Here str[0] pointing to String i.e. GEEKS and thus is accessed using .length()