Advertisement



< Prev
Next >





String length() method




As evident from its name, length() method of String class gives us the total number of characters in a String object.




Signature of length() method


public int length()






Note :


While calculating the total length of a String, the character at the first index is counted as 1 and not 0, i.e. one-based index .




length() example


In the upcoming example, we have initialized two String objects and we are calling length() method on each of these String objects to determine their length.
// Program to find the total length of a String.


class StringLen
{
public static void main(String[] ar)
{
String str1= new String("01234567");

System.out.println("First String is " + str1);
System.out.println("Length of first String is "+ str1.length());

System.out.println();
String str2= new String("String Chapter");

System.out.println("Second String is " + str2);
System.out.println("Length of second String is "+ str2.length());

}
}


Output is :


First String is 01234567
Length of first String is 8

Second String is String Chapter
Length of second String is 14


Program Analysis





Advertisement




Finding length of an empty String object.


In the upcoming example, we have finding length of a String object which is created but not initialized with a value.
// Program to find the length of an empty String object


class StringLen
{
public static void main(String[] ar)
{
String str1= new String();

System.out.println("String contains : " + str1);
System.out.println("Length of the String is "+ str1.length());

System.out.println();
str1 = "Today is Tuesday";

System.out.println("String after its initialization : " + str1);
System.out.println("Length of the String is "+ str1.length());

}
}


Output is :


String contains :
Length of the String is 0

String after its initialization : Today is Tuesday
Length of the String is 16


Program Analysis





Please share this article -




< Prev
Next >
< endsWith() method
charAt() method >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement