length and length() in Java


length and length in Java are used to check the length of the Array and the String. The main difference between length and length() is given below:

array.length : This is a variable used for checking length of arrays like string[], int[], float[].

string.length() : This is a method used for checking length of String objects or StringBuilder class in Java.

The main difference between length and length() is that length applies only to string[], int[], float[] and length() applies to String Object or StringBuilder.

Examples

Some examples on length variable and length() method.

Example for length variable

Following is the example for length variable which is used to check length of string array, integer array or float array.

public class Program1 { 
    public static void main(String[] args) 
    { 
	    // String array str_array[]
	    String[] str_array = { "Apple", "Mango", "Banana", "Pineapple" }; 

        // Integer Array int_array[]
        int[] int_array = { 10, 40, 50, 90, 100 }; 

        // Float Array float_array[]
        float[] float_array = { 1.21f, 83.42f, 56.39f, 87.80f, 28.80f };
        
	    System.out.println("length of String array is : " + str_array.length); 
        System.out.println("length of integer array is : " + int_array.length); 
        System.out.println("length of float array is : " + float_array.length);
    } 
}  

The output should be:

length of String array is : 4
length of integer array is : 5
length of float array is : 5

Example for length() method

Following is the example for length() method which is used to check length of String Objects or String Builder.

// Java program to illustrate the length() method 
public class Program2 { 
    public static void main(String[] args) 
    { 
        
	// String Object
	String temp = "Welcome to CrazyGeeks"; 
	System.out.println("Size of String is : " + temp.length()); 
    } 
} 

The output should be:

Size of String is : 21