1.

What is the difference between length and length () in Java?

Answer»

In Java, the length() is a method of String class whereas length is an instance VARIABLE of an array.

  • length in Java
    • The length variable returns the length of an array i.e. a number of elements present in an array.
    • After initializing, the length of an array cannot be changed, so the length variable can directly be used to get the length of an array.
    • It is used only for an array.
    • Example:
public class InterviewBit { public static VOID MAIN(String args[]) { int array[] = {1, 2, 3, 4, 5}; System.out.println("Length of an array is: " + array.length); }}

OUTPUT

Length of an array is: 5
  • length() in Java
    • It is a static method of String class.
    • The length() returns the number of characters stored in a string object.
    • The string class uses this method as the length of a string can be modified using the various operations performed on a string object.
    • The String class uses a char[] array internally.
    • Example:
public class InterviewBit { public static void main(String args[]) { String STR = "Welcome to InterviewBit"; System.out.println("Length of String using length() method is: " + str.length()); }}

Output:

Length of String using length() method is: 23


Discussion

No Comment Found