Precaution length vs length() vs size() Java

Precaution length vs length() vs size() Java

length vs length() vs size(): All the three length, length() and size() give the number of elements present but in different contexts.

A) length variable:

In Java, array (not java.util.Array) is a predefined class in the language itself. To find the elements of an array, designers used length variable (length is a field member in the predefined class). They must have given length() itself to have uniformity in Java; but did not. The reason is by performance, executing length variable is speedier than calling the method length(). It is like comparing two strings with == and equals(). equals() is a method call which takes more time than executing == operator.

int student[] = new int[5];
System.out.println(student.length); // prints 5

B) length() method:

It is a method defined in String class. It gives the number of characters present in the string.

String str = "hello";
System.out.println(str.length()); // prints 5

C) size() method:

It is used to find the number of elements present in collection classes. It is defined in java.util.Collection interface.

ArrayList al = new ArrayList();
System.out.println(al.size()); // prints 0 as no elements are added yet

A fresher should be careful while using length vs length() vs size().

View All for Java Differences on 90 Topics.

Leave a Reply

Your email address will not be published. Required fields are marked *