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.
1 | public int length() |
This method returns int containing the length of 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 = "Java String Length Example"; int stringLength = strObject.length(); System.out.println("String is: " + strObject); System.out.println("String length is: " + stringLength); } } |
Output
1 2 | String is: Java String Length Example String length is: 26 |
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
1 2 3 4 | String strObject = "Java String Length Example"; System.out.println("String length using length method: " + strObject.length()); System.out.println("String length without using length method: " + strObject.lastIndexOf("")); |
Output
1 2 | String length using length method: 26 String length without using length method: 26 |
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.
1 2 | String strObject = "Java String Length Example"; int length = strObject.toCharArray().length; |
OR
1 2 3 4 5 6 7 8 | String strObject = "Java String Length Example"; int stringLength = 0; for( char ch : strObject.toCharArray() ){ stringLength++; } System.out.println("String length is: " + stringLength); |
Output
1 | String length is: 26 |
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.
Add Comment