Java String length() Syntax
length() is a method of the String class. It takes no arguments and returns an int.
Java String Length Examples
The following are examples of finding the length of a string in Java. You can run any of these examples in the online Java code runner and paste your own text to count its characters.
Get the length of a string
Every character counts, including spaces. The string "Java is fun" has 9 letters and 2 spaces.
Check if a string is empty
isEmpty() returns true when length() is 0. isBlank() also returns true for a string that holds only spaces.
Get the length without leading and trailing spaces
trim() removes spaces, tabs and line breaks at both ends of the string. Call it before length() when the text comes from user input.
Count characters with codePointCount()
length() counts UTF-16 code units, and most emoji take two of them. codePointCount() counts Unicode code points, so the smiling face emoji 😀, written in the code as \uD83D\uDE00, counts as one.