CodeGym/Java Blog/Strings in Java/String length() Method
Author
Alex Vypirailenko
Java Developer at Toshiba Global Commerce Solutions

String length() Method

Published in the Strings in Java group
members

What is the length of a String?

“The length of a String in Java is equal to the number of characters in it. Including the alphabets, digits, spaces, and other special characters.”
For example, the length of the string “Hey, it’s finally summers!” is 26. String length() Method - 1

How to find the length of a String in Java?

Java provides a simple and handy method to compute the length of any String. Without further ado, let’s look at an example of finding String length.

Example

public class StringLength {
    public static void main(String args[]) {

      String alphabetsWithSpaces = "A B C";
      String digitsWithSpaces = "1 2 3";
      String specialCharsWithSpaces = "! @ $";
      String allChars = "Z X      3 $$$ ^^^ * )(";
      String sentence = "Hey, it's finally summers!";

      System.out.println(alphabetsWithSpaces + " length = " + alphabetsWithSpaces.length());
      System.out.println(digitsWithSpaces + " length = " + digitsWithSpaces.length());
      System.out.println(specialCharsWithSpaces + " length = " + specialCharsWithSpaces.length());
      System.out.println(allChars + " length = " + allChars.length());
      System.out.println(sentence + " length = " + sentence.length());
    }
}

Output

A B C length = 5 1 2 3 length = 5 ! @ $ length = 5 Z X 3 $$$ ^^^ * )( length = 23 Hey, it's finally summers! length = 26

Conclusion

By now you must be familiar with finding the String length in Java. However, if you still have any ambiguities don’t shy away from testing them out. Happy learning!String length() Method - 2
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet