How do I get the length of a string?


Working with strings under Java is far easier than with other languages. Most languages represent a string as a data type, or as an array of characters. Java however treats strings as an actual object, and provides methods that make string manipulation far easier.

Strings under Java are represented by the java.lang.String class. Since the java.lang package is imported by every Java application or applet, we can refer to it just as String. To determine the length of a String, simply call the String.length() method, which returns an int value.

String aString = "this is a string. what is my length?";
int length = aString.length();

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

TIP - Remember that the String class is zero-indexed. Even though the String is of length n, you can only access characters in the range 0..n-1