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.

The length() method in Java
The length() method in Java

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 name
int length = name.length(); //Calling the inbuilt lenght() method
System.out.println("The length of the String \""+name+"\" is: " +length); }
}

The length of the string name is 9:

1 of 12
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved