In Java, two different length constructs have different roles. 

 

".length", the length property is used with the String and Array class. It returns the number of characters in a text String or the size of an array. The length method, "length" with brackets"()", is for data encapsulation. 

 

The biggest similarity between them is that they help to determine the number of elements an object contains. However, the method works with the String class, while the property works with arrays. 

Here are some examples of them. 

// 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

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(array.length);  //4
 
        // Here str is a string object
        String str = "Meadow";
        System.out.println(str.length());  //6
    }
}

.length

public class Test {
    public static void main(String[] args)
    {
        // Here str is the array name of String type.
        String[] str = { "Java", "is", "easy", "and", "fun" };   //5
        System.out.println(str.length);
    }
}

length()

It will occur an error with this code.

public class Test {
    public static void main(String[] args)
    {
        String[] str = { "Meadow", "Min", "Young" };   //error
        System.out.println(str.length());
    }
}

 

'Java' 카테고리의 다른 글

Deleting attached files  (0) 2022.09.14
Java) Array  (0) 2022.09.04
Java) Conditional statements and loops  (0) 2022.08.30
Java) Data Types  (0) 2022.08.27
Java) Operators  (0) 2022.08.26

+ Recent posts