Skip to content

Java String length example

This Java example shows how to get the string length in Java using the length method and without using the length method.

What is String length?

Java String length is simply the number of characters (16-bit Unicode characters) the string object contains.

How to get String length in Java?

Use the length method of the String class to get the length of the string object.

This method returns a number of characters stored in the string.


How to get the length of the string without using the length method?

There is no better way to get the length other than using the built-in length method.

However, below given are some of the workarounds which could be used to get the length without using the length method.

1) Using the lastIndexOf() method of the String class


2) Using the toCharArray() method of the String class

The trick here is to convert the string to a character array and get the length of the array instead.



Is there any limit on the length of the string in Java?

Since the length method returns an int, the maximum length returned by this method could be Integer.MAX_VALUE which is 2^31 – 1.

This example is a part of the Java String tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.