array.length: length is the last variable that applies to the array. With the help of variable length we can determine the size of the array.
string.length(): The long() method is the last variable that applies to a String object. The long() method returns the number of characters present in the string.
length vs length():
// 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
3. We can use .length for direct access to array field elements; .Length() calls the method to access the field element.
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 = "GeeksforGeeks"; 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 13
Practice Questions based on the concept of length vs length()
Let’s have a look at the output of the following programs:
public class Test { public static void main(String[] args) { // Here str is the array name of String type. String[] str = { "GEEKS", "FOR", "GEEKS" }; System.out.println(str.length); } }
Output
3
Explanation: Here str is an array of type string and therefore str.length is used to specify the length.
public class Test { public static void main(String[] args) { // Here str[0] pointing to a string i.e. GEEKS String[] str = { "GEEKS", "FOR", "GEEKS" }; System.out.println(str.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() CANNOT be used to find its length.
public class Test { public static void main(String[] args) { // Here str[0] pointing to String i.e. GEEKS String[] str = { "GEEKS", "FOR", "GEEKS" }; System.out.println(str[0].length()); } }
Output
5
Explanation:
Here str[0] points to a string, i.e. GEEKS and hence can be called via .length()
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.