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.

Output

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

Output

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.

OR

Output

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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping