Java Data Type How to - Get the String length


We would like to know how to get the String length.


The String class contains a length() method that returns the number of characters in the String object.

The return type of the method length() is int. The length of an empty string is zero.

public class Main {
  public static void main(String[] args) {
    String str1 = new String();
    String str2 = new String("Hello");
//ww w . j a v a2  s . c o m
    // Get the length of str1 and str2 
    int len1 = str1.length();
    int len2 = str2.length();

    // Display the length of str1 and str2
    System.out.println("Length of  \"" + str1 + "\" = " + len1);
    System.out.println("Length of  \"" + str2 + "\" = " + len2);

The code above generates the following result.