Java String Handling

Java String length example

This Java example shows how to get the length of String in Java. This example also shows how to get the String length without using length() method in Java.

What is String length?

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

How to get length of String in Java?

Use length() method of String class to get the string length in Java.

This method returns int containing the length of the String.


How to get String length without using length() method?

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

Below are someĀ of the workarounds which could be used to get the string length without using the length() method of String.

1) Using lastIndexOf() method


2) Using toCharArray() method of String

Trick here is to covert the string to a character array and get the length of the array instead.



Is there any limit on String length in Java?

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

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