Java String length() Method With Examples

To find length of a String you can use length() method of the Java String class. This method returns the count of characters in the String object including spaces.

Java String length() method examples

1. In the examples there are two strings and length of those String is calculated using length() method.

public class StringLength {
  public static void main(String[] args) {
    String str1 = "String length method";
    //separated by 4 spaces
    String str2 = "Hello    World";
    System.out.println("Length of str1- " + str1.length());
    System.out.println("Length of str2- " + str2.length());
  }
}

Output

Length of str1- 20
Length of str2- 14

2- Printing each character by iterating a String, using String’s length() method to limit the iteration.

public class StringLength {
  public static void main(String[] args) {
    String str = "Hello";
    for(int i = 0; i < str.length(); i++) {
      System.out.println(str.charAt(i));
    }
  }
}

Output

H
e
l
l
o

Related Posts

That’s all for the topic Java String length() Method With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Share this post:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.