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 › length-vs-length-java
length vs length() in Java - GeeksforGeeks
January 4, 2025 - Explanation: Here the str is an array of type string and that's why str.length is used to find its length.
🌐
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?
Be careful not to confuse the String length() method with the length property of an array. The Java String length() method of an array is followed by round brackets, while the Java String length property is not.
🌐
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--

🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Java-length-vs-length-Whats-the-difference
Java length vs length(): What's the difference?
The key difference between Java’s length variable and Java’s length() method is that the Java length variable describes the size of an array, while Java’s length() method tells you how many characters a text String contains.
🌐
Tutorialspoint
tutorialspoint.com › home › java › java string length
Java String Length
September 1, 2008 - This method returns the the length of the sequence of characters represented by this object. import java.io.*; public class Test { public static void main(String args[]) { String Str1 = new String("Welcome to Tutorialspoint.com"); String Str2 = new String("Tutorials" ); System.out.print("String Length :" ); System.out.println(Str1.length()); System.out.print("String Length :" ); System.out.println(Str2.length()); } }
🌐
Javatpoint
javatpoint.com › java-string-length
Java String length() Method - javatpoint
Java String length() method with method signature and examples of concat, compare, touppercase, tolowercase, trim, length, equals, split, string length in java etc.
Top answer
1 of 5
34

The normal model of Java string length

String.length() is specified as returning the number of char values ("code units") in the String. That is the most generally useful definition of the length of a Java String; see below.

Your description1 of the semantics of length based on the size of the backing array/array slice is incorrect. The fact that the value returned by length() is also the size of the backing array or array slice is merely an implementation detail of typical Java class libraries. String does not need to be implemented that way. Indeed, I think I've seen Java String implementations where it WASN'T implemented that way.


Alternative models of string length.

To get the number of Unicode codepoints in a String use str.codePointCount(0, str.length()) -- see the javadoc.

To get the size (in bytes) of a String in a specific encoding (i.e. charset) use str.getBytes(charset).length2.

To deal with locale-specific issues, you can use Normalizer to normalize the String to whatever form is most appropriate to your use-case, and then use codePointCount as above. But in some cases, even this won't work; e.g. the Hungarian letter counting rules which the Unicode standard apparently doesn't cater for.


Using String.length() is generally OK

The reason that most applications use String.length() is that most applications are not concerned with counting the number of characters in words, texts, etcetera in a human-centric way. For instance, if I do this:

String s = "hi mum how are you";
int pos = s.indexOf("mum");
String textAfterMum = s.substring(pos + "mum".length());

it really doesn't matter that "mum".length() is not returning code points or that it is not a linguistically correct character count. It is measuring the length of the string using the model that is appropriate to the task at hand. And it works.

Obviously, things get a bit more complicated when you do multilingual text analysis; e.g. searching for words. But even then, if you normalize your text and parameters before you start, you can safely code in terms of "code units" rather than "code points" most of the time; i.e. length() still works.


1 - This description was on some versions of the question. See the edit history ... if you have sufficient rep points.
2 - Using str.getBytes(charset).length entails doing the encoding and throwing it away. There is possibly a general way to do this without that copy. It would entail wrapping the String as a CharBuffer, creating a custom ByteBuffer with no backing to act as a byte counter, and then using Encoder.encode(...) to count the bytes. Note: I have not tried this, and I would not recommend trying unless you have clear evidence that getBytes(charset) is a significant performance bottleneck.

2 of 5
17

java.text.BreakIterator is able to iterate over text and can report on "character", word, sentence and line boundaries.

Consider this code:

def length(text: String, locale: java.util.Locale = java.util.Locale.ENGLISH) = {
  val charIterator = java.text.BreakIterator.getCharacterInstance(locale)
  charIterator.setText(text)

  var result = 0
  while(charIterator.next() != BreakIterator.DONE) result += 1
  result
}

Running it:

scala> val text = "Thîs lóo̰ks we̐ird!"
text: java.lang.String = Thîs lóo̰ks we̐ird!

scala> val length = length(text)
length: Int = 17

scala> val codepoints = text.codePointCount(0, text.length)
codepoints: Int = 21 

With surrogate pairs:

scala> val parens = "\uDBFF\uDFFCsurpi\u0301se!\uDBFF\uDFFD"
parens: java.lang.String = 􏿼surpíse!􏿽

scala> val length = length(parens)
length: Int = 10

scala> val codepoints = parens.codePointCount(0, parens.length)
codepoints: Int = 11

scala> val codeunits = parens.length
codeunits: Int = 13

This should do the job in most cases.

🌐
Processing
processing.org › reference › string_length_
length() / Reference - String
Returns the total number of characters included in the String as an integer number. People are often confused by the use of length() to get the size of a String and length to get the size of an array.
Find elsewhere
🌐
Reddit
reddit.com › r/learnprogramming › x.length, x.length(), or length(x)?
r/learnprogramming on Reddit: x.length, x.length(), or length(x)?
September 16, 2021 -

In Java, there are functions that end with parentheses and there are some that don't, like x.length which is only used for arrays and x.length() only for strings. In Ruby, this is exactly the opposite. In JavaScript, x.length is used for both arrays and strings, so without parentheses, but then it's x.toUpperCase() which ends with parentheses...

And then in Python, it's len(x) (it could very well have been length(x)), where the variable is put inside the parenthesis as parameter to get the length of a string/array, but then it's x.upper() which again puts the variable outside of parentheses...

All languages aforementioned are objected oriented, but have their own way of calling upon the length functionality, which is super confusing. Is there a logic to why it's x.function, x.function(), or function(x)?

🌐
Software Testing Help
softwaretestinghelp.com › home › java › java string length() method with examples
Java String length() Method With Examples
April 1, 2025 - The last element is d which is at index[10]. So, the total length is 11. ... Answer: Character is nothing but the letter that combines together to form a String. Java also considers whitespaces as a character.
🌐
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.
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › length vs. length method in java
Length vs. Length Method in Java | Interview Kickstart
December 18, 2025 - Here’s a summary of the key differences between length and length(): ... Q. What will be the output of the following code? ... Explanation: In the above code, the variable “S” is an array of type strings. So, S.length can be used to get the length of the given array.
Address   4701 Patrick Henry Dr Bldg 25, 95054, Santa Clara
(4.7)
🌐
iO Flood
ioflood.com › blog › length-of-string-java
How to Find Length of String Java | Effective Methods
July 8, 2024 - Learn how to determine the length of string in Java using length() and other efficient methods. Understand java string length syntax with examples.
🌐
Codecademy
codecademy.com › docs › java › strings › .length()
Java | Strings | .length() | Codecademy
June 22, 2025 - Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more. Beginner Friendly.Beginner Friendly17 hours17 hours ... The .length() method requires no parameters. ... The .length() method returns a string’s length or number of characters.
🌐
DZone
dzone.com › data engineering › data › java string length confusion
Java String length confusion
April 21, 2014 - // Mathematical double-struck capital A String str = "\uD835\uDD38"; System.out.println(str); System.out.println(str.length()); //prints 2 · Which is correct according to the documentation, but maybe it’s not expected. You need to count the code points not the code units: String str = "\uD835\uDD38"; System.out.println(str); System.out.println(str.codePointCount(0, str.length()));
🌐
Quora
quora.com › What-is-the-difference-between-length-and-size-in-Java
What is the difference between length and size in Java? - Quora
Answer (1 of 4): * In java size is method which is written as size() which is available for collections. size() returns number of elements which is contain by collection (not the capacity). * where as .length is a field which works with arrays and gives capacity of arrays. * also length is a m...
🌐
Reddit
reddit.com › r/programming › string.length() vs string.getbytes().length in java
r/programming on Reddit: String.length() vs String.getBytes().length in Java
March 6, 2023 - There's no reason Java couldn't either. ... Oh, great! Introduce backwards incompatibility in a core data type, why don't you! ... Thank God this website is free. ... Create your account and connect with a world of communities. ... By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy. The best – but not good – way to limit string length...