Difference between length and length() in java - Java @ Desk

Monday, August 5, 2013

Difference between length and length() in java

length() - This is a method in java. It is a static method of String class. It returns the length of a string object i.e. number of characters stored in an object.
length - This is a instance variable of array of array in java. It returns the length of an array i.e. number of elements stored in an array.
length is used only for array where as length() is defined for String class.

Why array use the static variable whereas string class use the method?
Once arrays are initialized, its length cannot be changes, so a length variable can directly be used to get the length of an array.
String uses the method because the length of a string can be modified using the various operations on an object. Also the String class internally uses a char[] that it does not expose to the outside world.

public class LengthJava {

    public static void main(String args[]) {
        String name = "Kumar";
        int array[] = { 1, 2, 3, 4 };
        System.out.println("Length of string using length() method - " + name.length());
        System.out.println("Length of array using length keyword - " + array.length);
    }
}







2 comments:

  1. weird...............

    ReplyDelete
  2. is length keyword?
    what are differences ...please give 2 points........

    ReplyDelete