Java String length
Length of a string in java means the total number of characters that it contains.
If the string is made up of multiple words, then spaces are also counted as characters and hence, are included in the length of string.

String length() method
java.lang.String class has a length() method which returns an integer value as the length of string or the total number of characters in it.
Signature of length() method is

public int length()

length() does not take any arguments and returns an int value.
length() example
Below is an example program to get the length of a string using length() method.

public class StringLengthExample {
   public static void main(String[] a) {
     String s  = "codippa";
     int length = s.length();
     System.out.println("Length of " + s + " is " + length);
   }
}

Output is

Length of codippa is 7

length() can also be directly invoked on the string value rather than a string variable. Hence, above code can be shortened as

public class StringLengthExample { 
   public static void main(String[] a) { 
      int length = "codippa".length(); 
      System.out.println("Length is " + length); 
   } 
}

Get length of empty string
Empty string has no characters and hence its length should be zero. Let’s test it out with a simple program below

public class StringLengthExample { 
  public static void main(String[] a) { 
    int length = "".length(); 
    System.out.println("Length of empty string is " + length); 
  } 
}

Output is

Length of empty string is 0

length vs length()
Though both of these appear to be same but there are following important differences between the two.
1. length is a property while length() is a method.
2. length is applicable to arrays while length() is applicable to string
3. length returns the total number of elements in an array while length() returns the number of characters in a string.
Example of length is given below

int[] numbers = {1, 2, 3, 4};
// will be 4
int total = numbers.length;

That is all on string length() method to get the length or size of a string. Hope it was helpful.

0

Liked the article ? Spread the word...