To get the length of a string in Java, call the length() method on the string object, for example: String s = "hello"; int len = s.length(); — this returns the number of UTF-16 code units (usually characters) in the string. This method is part of the java.lang.String class and is available in every Java version.
Background: The String Class and Its length() Method
In Java, strings are objects of the String class, which is immutable (cannot be changed after creation). The length() method is defined in the String class and returns an int representing the number of characters in the string. It is a simple, parameterless method that has existed since Java 1.0. For example:
String greeting = "Hello, world!";
int size = greeting.length(); // size is 13
Note that the length is zero for an empty string ("".length() returns 0). The method does not count any null terminator (Java strings are not null-terminated like C strings).
How length() Works Under the Hood
Internally, a Java String stores its characters in a char[] array (or a byte array in some implementations for compact strings). The length() method simply returns the value of a private field that tracks the number of characters in that array. This field is set when the string is created and never changes because strings are immutable. Therefore, calling length() is an O(1) operation — it takes constant time regardless of the string’s length. It does not iterate over the characters; it just reads a stored integer.
Using length() in Real Code: Examples
Here are a few common use cases where you would call length():
- Looping over characters:
for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); } - Validating input: Check if a password has at least 8 characters:
if (password.length() < 8) { /* reject */ } - Truncating a string:
String short = longString.substring(0, Math.min(longString.length(), 100)); - Comparing lengths:
if (str1.length() != str2.length()) { /* different lengths */ }
Example with a full program:
public class Main {
public static void main(String[] args) {
String text = "Java";
System.out.println("Length: " + text.length()); // Output: Length: 4
}
}
Common Pitfalls and Misconceptions
One frequent mistake is confusing length() with the length property of arrays. In Java, arrays have a length field (no parentheses), while strings have a length() method (with parentheses). For example:
int[] numbers = {1, 2, 3};
int arrayLength = numbers.length; // correct
// int arrayLength = numbers.length(); // error: cannot find symbol
String word = "abc";
int stringLength = word.length(); // correct
// int stringLength = word.length; // error: cannot find symbol
Another misconception is that length() returns the number of visible characters (grapheme clusters). In fact, it returns the number of UTF-16 code units. For most characters (like ‘a’ or ‘Z’), one code unit equals one character. However, for supplementary characters (like emojis or some CJK characters) that are outside the Basic Multilingual Plane, Java uses surrogate pairs — two code units to represent one character. For example, the emoji 😀 has a length of 2, not 1:
String emoji = "😀";
System.out.println(emoji.length()); // Output: 2
If you need the number of Unicode code points (actual characters), use codePointCount(0, str.length()).
How to Choose: length() vs. Other Methods
Depending on your need, you might choose a different method:
length()— Use when you need the number of UTF-16 code units (most common for indexing, loops, and simple size checks).codePointCount(int beginIndex, int endIndex)— Use when you need the number of Unicode code points (true character count) for international text.isEmpty()— Use to check if a string has length 0:if (str.isEmpty())is clearer thanif (str.length() == 0).StringBuilder.length()— If you are using aStringBuilderorStringBuffer, they also have alength()method that returns the current length of the sequence.
Performance and Best Practices
Calling length() is extremely cheap, so you can call it as often as needed without performance concerns. However, there are a few best practices:
- If you are looping over a string and the length does not change, consider storing it in a local variable:
int len = str.length(); for (int i = 0; i < len; i++)— this avoids repeated method calls (though the JIT might optimize it anyway). - When comparing lengths, you can use
Integer.compare(str1.length(), str2.length())for sorting. - Be careful with very large strings:
length()returns anint, so the maximum length isInteger.MAX_VALUE(about 2.1 billion). In practice, you will never hit that limit.
Frequently Asked Questions
How do I get the length of a string in Java without using length()?
You could convert the string to a char array and use the array’s length property: char[] chars = str.toCharArray(); int len = chars.length;. However, this creates a new array and is less efficient. There is no built-in alternative that avoids length(); it is the standard and recommended way.
Why does length() return 2 for an emoji?
Because Java strings are encoded in UTF-16. Emojis and other characters outside the Basic Multilingual Plane (U+10000 to U+10FFFF) are represented as a pair of surrogate code units, each of which counts as one unit. So an emoji like 😀 (U+1F600) takes two code units, and length() returns 2. To count actual characters, use str.codePointCount(0, str.length()).
What is the difference between length() and length in Java?
length() is a method used on strings (and StringBuilder/StringBuffer). length is a public field used on arrays. For example, int[] arr = {1,2,3}; arr.length gives 3, while "abc".length() gives 3. Mixing them up causes compilation errors.
Can I use length() on a null string?
No. If a string variable is null, calling length() will throw a NullPointerException. Always check for null before calling the method, for example: if (str != null && str.length() > 0).
Does length() count spaces and punctuation?
Yes. Every character in the string counts, including spaces, tabs, punctuation, digits, and special characters. For example, "a b!".length() returns 4 (a, space, b, exclamation mark).
Is there a way to get the length of a string in bytes?
Yes, but that is different. To get the number of bytes when the string is encoded in a specific charset, use str.getBytes("UTF-8").length. For example, "é".getBytes("UTF-8").length returns 2 because é is encoded as two bytes in UTF-8. This is useful for network transmission or storage size.
Related
- Software Used for Data Entry? Top Tools Explained
- Random Number Generator Google: How to Use It
- Integrate Python into JMP: Step-by-Step Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Clean Excel File Online: Safe Steps and Best OptionsYes—you can clean an Excel file online by opening it in Excel for the web or by using…
- Create a Brochure in Microsoft Word: Layout, Steps and TipsTo create a brochure in Microsoft Word, start with a brochure template or set up a blank document…
- Excel Spreadsheet Not Responding? Causes and FixesIf an Excel spreadsheet is not responding, first stop clicking and give it a few minutes: a large…
- How to Present PowerPoint and See Your Speaker NotesTo present a PowerPoint while keeping your notes visible, connect a second display, set Windows to extend the…
- Excel Heatmap Formatting: Color Scales and TipsTo format a heatmap in Excel for Microsoft 365 on Windows, select the numeric cells, then choose Home…
- How to Create a Word Template with Fillable FieldsTo create a fillable Word template, add content controls from the Developer tab, set their properties, then save…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.