String Length can be defined as a total number of
Java Character present in a string object. For example, the string length of
"Note Book"
is 9 including the space character.
Methods used to obtain information about an object are known as accessor methods. One such accessor method is
length()
method, which returns the number of characters contained in the
String
object.
String Length
class StringLengthTest
{
public static void main(String arg[])
{
String place = "Hyderabad";
int length = place.length(); // LINE A
System.out.println("String Length of " + place + " is : " + length);
String welcome = "Welcome to Merit Campus";
for (int i = 0; i < welcome.length(); i++) // LINE B
{
System.out.print(welcome.charAt(i));
}
}
}
OUTPUTString Length of Hyderabad is : 9
Welcome to Merit Campus
DESCRIPTIONAt LINE A
, string length of "Hyderabad"
is calculated by length
method is stored in length
variable and displayed.
At LINE B
, for
loop executes 23 times as the length of "Welcome to Merit Campus"
string object is 23 and displays every character from beginning to end.
THINGS TO TRY
- Apply
length
method for different strings such as "12345"
, "Hello World"
, "Ramu\t\nRavi"
, "15-08-1947 00:25:30"
etc.,
- Apply
length
method in other control statements as used in for
loop at LINE B
.