length() String Example

November 3, 2014 | class String
Many methods exist in java.lang.String class used for different string manipulations like checking the availability of a character, to extract a part of a string or to convert a data type to string etc. Present method is on length() String.

Here is a simple length() method that returns the number of characters present in the string.

Following is the method signature

  • public int length(): Returns the number of characters present in the string as int value.
Following example illustrates the usage of length() String method.
public class StringMethodDemo
{
  public static void main(String args[])
  {
   String str = "hello";  	
   String str1 = "";  		// no space in between double quotes
   String str2 = "ok";  	
		
   int x = str.length();

   System.out.println("Number of characters in " + str + ": " +  x);
   System.out.println("Number of characters in empty string: " + str1.length());
   System.out.println("Number of characters in " + str2 + ": " +  str2.length());
   System.out.println("Number of characters in Hyderabad: " +  "Hyderabad".length());
  }
}

length() String Output screen on length() String Example

Pass your comments and suggestions on this tutorial "length() String Example".