Wednesday, September 13, 2017

length vs length() in Java

length vs length() in Java

Let me give you brief about length and length().

array.length : length is a final variable applicable for arrays. With the help of length variable, we can obtain the size of the array.

string.length() : length() method is a final variable which is applicable for string objects. length() method returns the number of characters presents in 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

So to directly accesses a field member of array we can use .length ; whereas .length() invokes a method to access a field member.

Sample Code:

public class Test {
public static void main(String[] args)
    {
        int[] array = new int[4];
        System.out.println("The size of the array is " + array.length);

        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


No comments: