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.
1 |
public int length() |
This method returns a number of characters stored in the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javacodeexamples.stringexamples; public class StringLengthExample { public static void main(String args[]){ String strObject = "I Love Java"; int stringLength = strObject.length(); System.out.println("String is: " + strObject); System.out.println("length is: " + stringLength); } } |
Output
1 2 |
String is: I Love Java length is: 11 |
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
1 2 3 4 |
String strObject = "I Love Java"; System.out.println("Using the length method: " + strObject.length()); System.out.println("Without using the length method: " + strObject.lastIndexOf("")); |
Output
1 2 |
Using the length method: 11 Without using the length method: 11 |
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.
1 2 |
String strObject = "Hello World"; int length = strObject.toCharArray().length; |
OR
1 2 3 4 5 6 7 8 |
String strObject = "Hello World"; int stringLength = 0; for( char ch : strObject.toCharArray() ){ stringLength++; } System.out.println("Length is: " + stringLength); |
Output
1 |
String length is: 11 |
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.