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.

Output

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

Output

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.

OR

Output

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.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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