length variable vs length() method
length variable
length
is a final variable applicable to arrays. length
variable represents the size of the array.
import java.lang.*;
class Test {
public static void main(String[] args) {
int[] = new int[6];
System.out.println(x.length()); // INVALID: compile-time error - cannot find symbol: method length(), location: class int[]
System.out.println(x.length); // VALID: 6
}
}
length() method
length()
method is a final method applicable for String
objects. length()
method returns the number of characters present in the String
.
import java.lang.*;
class Test {
public static void main(String[] args) {
String s = "abc";
System.out.println(s.length); // INVALID: length variable not applicable to string: compile-time error - cannot find symbol: vairable length, location: class java.lang.String
System.out.println(s.length()); // VALID: 3
}
}
Differences between length variable and length() method
length
variable is applicable to arrays, but not for String
objects. Whereas length()
method is applicable for String
objects, but not for arrays.
import java.lang.*;
class Test {
public static void main(String[] args) {
String[] s = {"A","AA","AAA"};
System.out.println(s.length); // VALID: 3
System.out.println(s.length()); // INVALID: compile-time error: cannot find symbol: method length(), location: class String[]
System.out.println(s[0].length); // INVALID: length variable not applicable to string: compile-time error - cannot find symbol: vairable length, location: class java.lang.String
System.out.println(s[0].length()); // VALID:
}
}
length variable in multi-dimensional arrays
In multi-dimensional arrays, length
variable represents only the base size, not the total size of the array.
import java.lang.*;
class Test {
public static void main(String[] args) {
int[][] x = new int[6][3];
System.out.println(x.length); // VALID: 6
System.out.println(x[0].length); // VALID: 3
}
}
There is no direct way to find total length of a multi-dimensional array. it can be done indirectly by finding the total sum of the sub-arrays:
import java.lang.*;
class Test {
public static void main(String[] args) {
int[][] x = new int[6][3];
System.out.println(x.length); // VALID: 6
System.out.println(
x[0].length
+x[1].length
+x[2].length
+x[3].length
+x[4].length
+x[5].length
); // VALID: 18
}
}