The length of a string
is referred to as the total number of characters it contains.
To calculate the length of a string in Java, you can use an inbuilt length()
method of the Java string class.
In Java, strings are objects created using the string class and the length()
method is apublic
member method of this class. So, any variable of type string
can access this method using the .
(dot) operator.
The length()
method counts the total number of characters in a String.
The signature of the length()
method is as follows:
public int length()
The return type of the length() method is int
.
Let’s calculate & printout the length of a string
using the length()
method.
class CalcLength {public static void main( String args[] ) {String name = "educative"; //Initilizing a String Object nameint length = name.length(); //Calling the inbuilt lenght() methodSystem.out.println("The length of the String \""+name+"\" is: " +length); }}
The length of the string name
is 9:
Free Resources