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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.length()

Return value

An int.

Examples

Count characters
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.

Validate a minimum length
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

VersionChange
Java Java 1.0Added

Was this page helpful?