
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the differences between length and length () in Java?\\n
In Java, both the length property and the length() method are used to determine the size of data, or we can say they help us to find the number of elements an object contains.
However, they are used with different Java objects. The length is an instance variable used for arrays, whereas length() is a method used with String objects.
In this article, we are going to discuss the difference between length and length() in Java.
The length Property
An array is an object that holds a fixed number of values of the same type. Its length variable is used to find the number of elements in that array. It is a final variable that is directly accessible through the array objects.
Example
The following example illustrates the use of length property:
public class ArrayLengthTest { public static void main(String args[]) { int array[] = {1, 2, 3, 4, 5, 6, 7}; System.out.println("Length of an array is: " + array.length); } }
On running the above Java program, you will get the following result:
Length of an array is: 7
The length() Method
The String class internally uses a char[] array that it does not expose to the outside world directly. Instead, it provides the length() method, which is used to return the number of characters in a string.
Example
In this example, we will see the use of length() method.
public class StringLengthMethodTest { public static void main(String args[]) { String str = "Welcome to Tutorials Point"; System.out.println("Length of String using length() method is: " + str.length()); } }
When you run the above Java program, it will display the following output:
Length of String using length() method is: 26
Difference between length Property and length() Method
The table below compares and discusses the difference between length and length() in Java:
length Property |
length() Method |
---|---|
The length is an instance variable of an array. |
The length() is a method of the String class. |
It returns the length of an array, i.e., the number of elements stored in an array. |
It returns the length of a string object i.e., the number of characters stored in the string object. |
Once arrays are initialized, their length cannot be changed, so the length property can be used directly to get the length of an array. |
String class uses the length() method because the length of a string can be modified using the various operations on an object. |