• str.toCharArray().length should work.

  • Or how about:

    str.lastIndexOf("")

    Probably even runs in constant time :)

  • Another one

    Matcher m = Pattern.compile("$").matcher(str);
    m.find();
    int length = m.end();
    
  • One of the dumbest solutions: str.split("").length - 1

  • Is this cheating: new StringBuilder(str).length()? :-)

Answer from aioobe on Stack Overflow
🌐
PREP INSTA
prepinsta.com › home › dsa in java › java program to find length of the string without using length function
Java program to find length of String without using length method
October 14, 2022 - // Without length() char[] ch = str.toCharArray(); System.out.println(“Length of String : “+ch.length); } } ... class HelloWorld { public static void main(String[] args) { String str = “sarithra”; int count=0; char[]ch = str.toCharArray(); ...
🌐
Blogger
javarevisited.blogspot.com › 2020 › 04 › 5-ways-to-find-length-of-string-in-java.html
5 ways to find length of String in Java - Example Tutorial
By knowing this, you can think of many approaches to calculating length e.g. getting a char array from String and counting a number of characters or many are by applying some clever tricks. In this article, we are going to look at some unorthodox approaches of finding String length in Java, all of these don't use the built-in length() method but make use of Java API.
🌐
Java2Blog
java2blog.com › home › core java › java programs › how to find length of string in java without using length() method
How to find length of string in java without using length() method - Java2Blog
January 12, 2021 - Initialize i with 0 and iterate over String without specifying any condition. So it will be always true. Once value of i will be more than length of String, it will throw StringIndexOutOfBoundsException exception. We will catch the exception and return i after coming out of catch block.
🌐
Coderanch
coderanch.com › t › 523853 › java › String-length-String-length-method
String length without using String.length() method (Beginning Java forum at Coderanch)
From the subject line, the only restriction is on use of String#length(). So I would expect that it's allowed to use String#toCharArray().length edit I see the OP mentions 'length properties' so I guess that rules that out. luck, db There are no new questions, but there may be new answers. ... How about creating a JLabel with a monospace font and this text and then inferring the length from the preferred size of the JLabel? Is that indirect enough? ... without using any built in length methods or length properties.
🌐
Blogger
javahungry.blogspot.com › 2013 › 06 › find-length-of-string-calculate-without-using-built-in-functions-code-program.html
Length of the String without using java built in length method : Java code with example | Java Hungry
The length of the string is easy to define , it is the number of characters in the string including white spaces . Java make the things easy as it provides the built in length method for the String class (java.lang.String) which is a final class . for example : String demo = " This is java built in method example " int length= demo.length(); But what happens , if we don't want to use the java built in method to calculate the length of the string .
Find elsewhere
🌐
Make Selenium Easy
makeseleniumeasy.com › home › java programs 16: java program to find length of string without using length method
Java Programs 16: Java Program to Find Length of String Without Using Length Method - Make Selenium Easy
February 19, 2025 - In this post, I will find length of string without using Length method but using some other method. :-p · There is another method in String class called lastIndexOf(). ... Returns the index within this string of the last occurrence of the specified substring. The last occurrence of the empty string “” is considered to occur at the index value this.length(). Highlighted in bold in above string is my solution actually.
🌐
Coderanch
coderanch.com › t › 381374 › java › find-length-String-length-method
How to find the length of a String without using the length method (Java in General forum at Coderanch)
November 6, 2006 - and what did you answer in the interview ? as Peter said: check out the API for java.lang.String pascal ... Hi, If you do not want to use length() method of string then treat String as array of Character .and use a loop.i think you will be known about it.
🌐
W3Schools
w3schools.com › java › ref_string_length.asp
Java String length() Method
Note: The length of an empty string is 0. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, ...
🌐
Upgrad
upgrad.com › home › blog › software development › what is string length java? methods to find string length with examples
Explore String Length Java: Key Methods & Use Cases
June 17, 2025 - Output: Length using char array: 10 Explanation: The PAN number "ABCDE1234F" has 10 characters, each stored as a single char. toCharArray().length reflects this directly, without invoking additional string methods. ... In certain string length Java scenarios, especially when working in constrained environments or applying custom logic, counting characters manually using a loop provides flexibility.
🌐
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?
To find the length of a String, make sure you invoke the length() method, not the length property. There are many scenarios where a program must first find the length of a Java String.
🌐
Talent Battle
talentbattle.in › important-coding-questions-for-placement › print-length-of-the-string-without-strlen-function
Program to Print Length of the string without strlen() function | Talent Battle
April 26, 2023 - Learn how to Print Length Of The String Without Using Strlen Function. Practice various problems for coding tests and interview preparation.
🌐
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--

🌐
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.
🌐
Quora
quora.com › How-do-I-find-the-length-of-a-string-without-using-a-length-function-or-loops-in-any-programming-language
How to find the length of a string without using a length function or loops in any programming language - Quora
Answer (1 of 10): Hi, Try this: string s= “your string”; printf(“%d”,printf(“%s”,s)); The output that you will get would be this. your string11 The string you entered followed by the length of the same string. This happens because of the printf function.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › find-the-length-of-a-string
Length of a String - GeeksforGeeks
July 23, 2025 - Given a string s, the task is to find the length of the string.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › string length in java
String length() Method in Java – Syntax, Example & Use Cases
April 30, 2025 - It operates in constant time O(1) ... value, without scanning the string characters. Internally, Java strings are stored as character arrays. The length is either the array's length or a separate count field, accessed directly when you call length(). If two strings have the same number of characters ...
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.

🌐
GoLinuxCloud
golinuxcloud.com › home › programming › java string length examples [multiple scenarios]
Java string length Examples [Multiple Scenarios] | GoLinuxCloud
February 22, 2022 - We learned how we can use the length method available in java to find the length of a string by taking various examples. Moreover, we also covered how we can find the total number of whitespaces in a string and how we can find the length of a string without counting the whitespaces.