Get the Length of a String in Java

The length of a String is the number of its characters. To get the length of a String in Java, we can use the length() method from the String class.

Example:

public class Test {

  public static void main(String[] args) {

    String str = "Learn Java with alegrucoding.com";

    System.out.println(str.length());

  }
}
Output: 32
 
Also, we can use the for loop to count characters in a String.

Example:

public class Test {

  public static void main(String[] args) {
    int count = 0;

    String str = "Learn Java with alegrucoding.com";

    for (int i = 0; i < str.length(); i++) {
      count++;
    }

    System.out.println(count);

  }
}
Output: 32
 
That’s it!
 
Happy coding!

Leave a Reply

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