Java String length() Method

In Java, the length() method of the String class is used to find the number of characters in a string. It returns an int value representing the total count of Unicode code units (characters) in the string, including letters, digits, spaces, punctuation, and special characters.

  • Syntax: string.length()

  • Return Type: int

  • Examples:

    String greeting = "Hello, World!";
    System.out.println(greeting.length()); // Output: 13
  • Key Points:

    • Counts all characters, including whitespace and special symbols.

    • The maximum length of a string is 2,147,483,647 (2^31 - 1), limited by the int data type.

    • Efficient: operates in O(1) time complexity, as it returns a pre-stored length value.

    • Not the same as array.length (arrays use .length without parentheses).

    • Can be used with StringBuilder and StringBuffer classes as well.

⚠️ Note: Calling length() on a null string will throw a NullPointerException. Always ensure the string is not null before calling the method.

Best practices and conventions evolve with time. The String class was made in Java 1.0, and the convention just hadn't been established. Answer from WrickyB on reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-length-method-with-examples
Java String length() Method - GeeksforGeeks
December 23, 2024 - The length() method returns the number of characters present in the string.
🌐
W3Schools
w3schools.com › java › ref_string_length.asp
Java String length() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... The length() method returns the length of a specified string.
Discussions

Why is it String.length() instead of String.getLength()? How to name my own length method?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
13
7
September 13, 2023
how to write java string length method code? - Stack Overflow
what is the wrong of the following code , i am trying to write the length method source code , i tried it with c++ ( same logic i mean ) and it worked , but here it give me the below exception erro... More on stackoverflow.com
🌐 stackoverflow.com
String's Maximum length in Java - calling length() method - Stack Overflow
Great answer man! I took a look on String.java source code and it's right, 'count' is the int variable who returns the length of the char array, and the char array is stored on the 'value' variable (as char [ ]) It means that the String size could be around 2GB. More on stackoverflow.com
🌐 stackoverflow.com
[Java] How is the running time of string concatenation O(n^2)?
Roughly speaking, you can think of strings as immutable arrays of characters. Then, "Hello" + "World" would be equivalent to taking the char array ['H', 'e', 'l', 'l', 'o'], and the char array ['W', 'o', 'r', 'l', 'd'], and then creating a new array (of length 10) with the combined letters in both inputs. Therefore, concatenating a string of length n and a string of length m takes O(n + m) time. That said, it is worth noting that for compile-time constants, any decent compiler will precompute concatenated strings. In addition, modern compilers will generally also optimize a fixed amount of string concatenations. This basically just leaves the advice "don't concatenate strings in a loop". More on reddit.com
🌐 r/learnprogramming
7
30
July 19, 2016
People also ask

How do you find the length of a String in Java?
In Java, you find the length of a String using the length() method. It returns an integer representing the number of characters, including spaces and symbols, in the string. Example: str.length();
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string length in java
String length() Method in Java – Syntax, Example & Use Cases
How do you find the length of a String array in Java?
To find the number of elements in a String array, use the .length property without parentheses. Example: stringArray.length; This counts the number of elements, not characters.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string length in java
String length() Method in Java – Syntax, Example & Use Cases
What is the difference between String length() and array length in Java?
In Java, strings use the length() method with parentheses, while arrays use the length property without parentheses. Both provide the count of elements or characters.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string length in java
String length() Method in Java – Syntax, Example & Use Cases
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
October 20, 2025 - Constructs a new String by decoding the specified subarray of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Find-Java-String-Length-Example-Tutorial
How do I find the Java String length?
The String length method includes the whitespace padding at the beginning and the end of the String. Quite often, when validating input or manipulating text, you want to eliminate leading and trailing whitespace. This can be achieved through the use of the Java String’s trim method.
🌐
Reddit
reddit.com › r/learnjava › why is it string.length() instead of string.getlength()? how to name my own length method?
r/learnjava on Reddit: Why is it String.length() instead of String.getLength()? How to name my own length method?
September 13, 2023 -

Hi, I've been trying to find a name for my method that returns the length of an object. A quick google search showed that it's conventional to name getters getX(). However, when I investigated the first standard class that came to mind - String, I found it having the length() method instead of expected getLength(). Why is that? How should I name a length method in my own class then?

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#length--

Find elsewhere
🌐
CodeGym
codegym.cc › java blog › strings in java › string length() method
String length() Method
May 30, 2022 - public class StringLength { public static void main(String args[]) { String alphabetsWithSpaces = "A B C"; String digitsWithSpaces = "1 2 3"; String specialCharsWithSpaces = "! @ $"; String allChars = "Z X 3 $$$ ^^^ * )("; String sentence = "Hey, it's finally summers!"; System.out.println(alphabetsWithSpaces + " length = " + alphabetsWithSpaces.length()); System.out.println(digitsWithSpaces + " length = " + digitsWithSpaces.length()); System.out.println(specialCharsWithSpaces + " length = " + specialCharsWithSpaces.length()); System.out.println(allChars + " length = " + allChars.length()); System.out.println(sentence + " length = " + sentence.length()); } }
🌐
Codekru
codekru.com › home › java string length() method
Java String length() method - Codekru
June 19, 2022 - java · length() method tells us about the size of the string. In this post, we will discuss the length() method of the String class in detail. Method declaration – public int length(). What does it do and return? It helps in returning the size of the string.
Top answer
1 of 7
188

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

2 of 7
32

java.io.DataInput.readUTF() and java.io.DataOutput.writeUTF(String) say that a String object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput and DataOutput.

In addition, The specification of CONSTANT_Utf8_info found in the Java virtual machine specification defines the structure as follows.

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

You can find that the size of 'length' is two bytes.

That the return type of a certain method (e.g. String.length()) is int does not always mean that its allowed maximum value is Integer.MAX_VALUE. Instead, in most cases, int is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int are converted to int before calculation (if my memory serves me correctly) and it is one reason to choose int when there is no special reason.

The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String object.

String objects may be able to have much more characters at runtime. However, if you want to use String objects with DataInput and DataOutput interfaces, it is better to avoid using too long String objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF() and DataOutput.writeUTF(String).

🌐
Upgrad
upgrad.com › home › tutorials › software & tech › string length in java
String length() Method in Java – Syntax, Example & Use Cases
April 30, 2025 - Learn how to use the length() method in Java to find the number of characters in a string. Explore syntax, examples, and common use cases for better string handling.
🌐
Baeldung
baeldung.com › home › java › java string › java’s string.length() and string.getbytes().length
Java’s String.length() and String.getBytes().length | Baeldung
July 6, 2024 - String s = "beautiful"; assertEquals(9, s.length()); assertEquals(9, s.getBytes().length); When dealing with a string in Java, is it guaranteed that String.length() and String.getBytes().length always yield the same value? Next, let’s figure it out. The default character encoding or charset of the current JVM plays an important role in deciding the result of String.getBytes().length.
🌐
DataFlair
data-flair.training › blogs › java-string-length-method
Java String length() Method with Examples - DataFlair
July 18, 2024 - The length() method returns an int value, which is the number of Unicode code units in the string. This value ranges from 0 for an empty string to 2,147,483,647 for a string containing the maximum number of Unicode code units.
🌐
CodeAhoy
codeahoy.com › java › string-length
Java String Length() Method with Examples | CodeAhoy
January 26, 2020 - The String class contains many useful string methods. To find the length of a string in Java, we can use the length() method of the String class. This method is called on the string object whose length you want to find. It takes no parameters and returns the number of characters (length) as an int.
🌐
Programiz
programiz.com › java-programming › library › string › length
Java String length()
The length is equal to the number of characters (code units) in the string. class Main { public static void main(String[] args) { String str1 = "Java"; String str2 = ""; System.out.println(str1.length()); // 4 System.out.println("Java".length()); // 4 // length of empty string System.out.p...
🌐
Educative
educative.io › answers › how-to-find-the-length-of-a-string-in-java
How to find the length of a string in Java
To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-length-method-example
Java String length() Method with examples
This method counts the number of characters in a String including the white spaces and returns the count. ... This method returns an integer number which represents the number of characters (length) in a given string including white spaces.
🌐
Lobsters
lobste.rs › s › ad6z4g › string_length_vs_string_getbytes_length
String.length() vs String.getBytes().length in Java | Lobsters
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length() This does say · Returns the length of this string. The length is equal to the number of Unicode code units in the string. and · the length of the sequence of characters ...
🌐
Codecademy
codecademy.com › docs › java › strings › .length()
Java | Strings | .length() | Codecademy
June 22, 2025 - In Java, the .length() method returns the length or number of characters in a string. It’s a built-in method that comes with the String class.
🌐
Coderanch
coderanch.com › t › 523853 › java › String-length-String-length-method
String length without using String.length() method (Beginning Java forum at Coderanch)
January 17, 2011 - Rob Prime wrote:Ah right. I never think of these nasty ways. Using exceptions for control flow is just bad. You could always just cast the String to lower case, add an "A" to the end and then call indexOf, that would give you the length and no exception