what is difference between length and length method in java

What is difference between length and length() method in java with example

In Java, length and length() are used to get the size or length of different types of data structures. They are used for arrays and strings respectively.

length (for Arrays):

length is a property of arrays in Java, used to get the size or length of the array. It is not a method but a public final instance variable.

Here’s an example:

length example
/*
 * Author: Zameer Ali
 * */
int[] numbers = {1, 2, 3, 4, 5};
int arrayLength = numbers.length;
System.out.println("Array length: " + arrayLength); // Output: Array length: 5

In this example, numbers.length returns the number of elements in the array numbers, which is 5.

length() (for Strings):

length() is a method available for strings in Java, used to get the number of characters in the string. It is a method, not a property, and is called using parentheses.

Here’s an example:

length() function example
/*
 * Author: Zameer Ali
 * */
String text = "Hello, World!";
int stringLength = text.length();
System.out.println("String length: " + stringLength); // Output: String length: 13

In this example, text.length() returns the number of characters in the string text, which is 13.

In summary:

  • length is a property of arrays in Java, used to get the size of the array.
  • length() is a method available for strings in Java, used to get the number of characters in the string.

Leave a Reply

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