Java 25 (LTS) reference · String Methods
Java String length() Method
Return the number of characters (UTF-16 code units) in a string. An empty string has length 0.
Java 25 (LTS) Since Java 1.0
Syntax
string.length()
Return value
An int.
Examples
public class Main {
public static void main(String[] args) {
String name = "ReadyCamel";
System.out.println(name.length());
System.out.println("".length());
}
}
Output
10 0
Run this on your computer — see “Get Started” for setup.
public class Main {
public static void main(String[] args) {
String password = "hunter2";
if (password.length() < 8) {
System.out.println("Password must be at least 8 characters");
}
}
}
Output
Password must be at least 8 characters
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
string.isBlank()· Return true if the string is empty or contains only whitespace. isEmpty() is true only for "".string.charAt()· Return the character at an index (0-based). Throws StringIndexOutOfBoundsException for an invalid index.- Java Strings · tutorial