Programming
String Length
Coding Tutorial
Java
Computer Science

Get the length of a String

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Java, the usual way to get the length of a string is text.length(). That answer is correct for many day-to-day tasks, but the deeper detail is that Java counts UTF-16 code units, not always human-perceived characters.

The Basic Method: length()

Every String in Java has a length() method that returns an int.

java
1public class Main {
2    public static void main(String[] args) {
3        String text = "Hello";
4        System.out.println(text.length());
5    }
6}

This prints 5, because there are five UTF-16 code units in the string.

For ordinary ASCII text, that matches what most people think of as the number of characters. That is why length() is usually enough for validation rules, substring bounds, and simple parsing.

What length() Really Counts

Java strings are stored as sequences that conceptually use UTF-16 indexing. That means some Unicode characters use one code unit and others use two.

For example, many emoji are represented as surrogate pairs:

java
1public class Main {
2    public static void main(String[] args) {
3        String emoji = "🙂";
4
5        System.out.println(emoji.length());
6        System.out.println(emoji.codePointCount(0, emoji.length()));
7    }
8}

In this case, length() returns 2, while codePointCount(...) returns 1.

That difference matters when you are:

  • counting displayed characters
  • validating character limits in user-facing text
  • iterating over Unicode safely

If the requirement is truly “number of Java string positions,” use length(). If the requirement is “number of Unicode code points,” use codePointCount.

When length() Is the Right Tool

length() is still the correct choice for many common programming tasks:

  • checking whether a string is empty
  • enforcing a storage or protocol limit based on Java string length
  • validating whether an index is safe
  • writing ordinary business logic over mostly ASCII or simple text

Example:

java
1public class Main {
2    public static void main(String[] args) {
3        String password = "abc123";
4
5        if (password.length() < 6) {
6            System.out.println("Too short");
7        } else {
8            System.out.println("Accepted");
9        }
10    }
11}

This is a completely reasonable use of length().

When You Should Count Code Points Instead

If your application is user-facing and supports international text, code point counting is often safer.

java
1public class Main {
2    public static void main(String[] args) {
3        String text = "A🙂B";
4
5        int utf16Length = text.length();
6        int codePoints = text.codePointCount(0, text.length());
7
8        System.out.println("UTF-16 length: " + utf16Length);
9        System.out.println("Code points: " + codePoints);
10    }
11}

That string visually looks like three characters, but length() counts four UTF-16 code units because the emoji uses two units.

This distinction appears in UI validation, social features, messaging systems, and any workflow where users care about what they see on screen rather than what Java stores internally.

Empty Strings and null

A common beginner issue is mixing up an empty string and a null reference.

java
1public class Main {
2    public static void main(String[] args) {
3        String empty = "";
4        String missing = null;
5
6        System.out.println(empty.length());
7
8        if (missing != null) {
9            System.out.println(missing.length());
10        }
11    }
12}

"" has length 0. But calling .length() on null throws NullPointerException. That is not a string-length problem; it is a reference-safety problem.

If null is possible, guard against it before calling the method.

Iterating Based on Length

Since length() gives you the upper bound for Java string indexing, it is often used in loops:

java
1public class Main {
2    public static void main(String[] args) {
3        String text = "Java";
4
5        for (int i = 0; i < text.length(); i++) {
6            System.out.println(text.charAt(i));
7        }
8    }
9}

This works well for simple text. But once again, if you need Unicode correctness for code points beyond the Basic Multilingual Plane, iterating with charAt(i) may split surrogate pairs. In that case, iterate by code point instead of by individual char values.

Common Pitfalls

The most common pitfall is assuming length() always equals the number of visible characters. That is not true for all Unicode text.

Another mistake is calling .length() on a null reference. An empty string and a missing string are different situations.

A third issue is using charAt and length() together on emoji-heavy text without understanding surrogate pairs. The code may run, but it can still mis-handle characters.

Finally, developers sometimes overcomplicate ordinary cases. For plain ASCII-style validation, length() is usually exactly the right tool.

Summary

  • In Java, get a string’s length with text.length().
  • 'length() counts UTF-16 code units, not always user-visible characters.'
  • Use codePointCount when Unicode-aware character counting matters.
  • Guard against null before calling .length().
  • For simple application logic, length() remains the normal and correct API.

Course illustration
Course illustration

All Rights Reserved.