Get the length of a String
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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.
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:
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:
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.
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.
"" 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:
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
codePointCountwhen Unicode-aware character counting matters. - Guard against
nullbefore calling.length(). - For simple application logic,
length()remains the normal and correct API.
Related reading
- Get the POST request body from HttpServletRequest
- Get type of a generic parameter in Java with reflection
- Get Value of a Edit Text field
- Get value of a public static field via reflection
- getResourceAsStream returns null
- getResourceAsStream vs FileInputStream
- getString Outside of a Context or Activity
- Getting Ambiguous ExceptionHandler method mapped for MethodArgumentNotValidException while startup of spring boot application

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.