How to find the length of a string in Java
The length of a string is referred to as the total number of characters it contains.
The length() method
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.
Method signature
The signature of the length() method is as follows:
public int length()
The return type of the length() method is int.
Example
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:
1 of 12
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved