How to Find Length of String in Java

How to Find Length of String in Java? Java provides a built-in function to find the length of a string:- length(), and its return type is int. Also see:- Length of String in Java Without Using length() Method

Method Syntax:- public int length(). It returns an integer value, which is the length of the given string. Example:-

public class Main {
    public static void main(String args[]) {
        String str = "Know Program";
        System.out.println(str.length());
    }
}

Output:-

12

Find the Length of a String in Java Without Using length() Method

We can also find the length of a string in Java without using the length() method and to do this we can take the help of any loop. We will iterate through the string from the start to the end of the character and will count the number of iterations. The number of iterations gives the length of the string.

Find the Length of a String in Java using for loop

public class Test {
    public static void main(String args[]) {
        String str = "Know Program";
        int length = 0;
        try {
            while (true) {
                str.charAt(length);
                length++;
            }
        } catch (StringIndexOutOfBoundsException e) {
        }
        System.out.println(str.length());
    }
}

Output:-

12

The charAt() method of the string class fetches the character at the given index, and if we try to access a character at an index less than 0 or greater (where there is no character) then this method throws Java.lang.StringIndexOutOfBoundsException.

In the above program, the length variable is initialized with 0 therefore it will fetch the first character of the string. Since while contains true therefore it should run infinitely. But when it tries to fetch a character at an index greater than the length of the string, at that time, charAt() method throws StringIndexOutOfBoundsException, and control of the program came to catch block (outside of try block and while loop). Finally, the length variable contains the length of the string.

Java String Length Limit

In this section, we discuss the length limit of the String. A string is a sequence of characters and it is mutable i.e. once created it cannot be changed. The length of the string is usually equal to the Unicode units in the string.

The length method returns the integer value hence the max length of the string would be -231 to 231 – 1 that is -2147483648 to 2147483647. As we cannot use a negative value for indexing, the indexing is done from 0 to 2147483647. Hence we can have a string length of up to 2,147,483,647. 

Observe the snippet below it demonstrates the maximum string length and the space available in the heap. For this, we have used Integer.MAX_VALUE stores the maximum possible value of the integer. 

import java.util.Arrays;

public class Main {
   public static void main(String args[]) {
      for (int i = 0; i < 1000; i++) {
         try {
            char[] arr = new char[Integer.MAX_VALUE - i];
            Arrays.fill(arr, 'a');
            String string = new String(arr);
            System.out.println(string.length());
         } catch (Throwable e) {
            System.out.println(e.getMessage());
            System.out.println("Last: " + (Integer.MAX_VALUE - i));
            System.out.println("Last: " + i);
         }
      }
   }
}

Output:

Requested array size exceeds VM limit
Last: 2147483647
Last: 0
Requested array size exceeds VM limit
Last: 2147483646
Last: 1
Java heap space
Last: 2147483645
Last: 2
Java heap space
Last: 2147483644
Last: 3
Java heap space
Last: 2147483643
Last: 4
Java heap space
Last: 2147483642
Last: 5
Java heap space
Last: 2147483641
Last: 6
Java heap space
Last: 2147483640
Last: 7
Java heap space
Last: 2147483639
Last: 8
Java heap space
Last: 2147483638
Last: 9

String Array Length In Java

Now we will find the length of an array in this section previously we used to use length() to find the length of the string but to find the length of the array we use the length property of the array.

public class Main {
   public static void main(String[] args) {
      String[] arr = { "Java", "Python", "C", "C++", "HTML" };
      System.out.println("String array length: " + arr.length);
   }
}

Output:

String array length: 5

How To Limit String Input Length In Java

Now, we will see how to limit the string input in Java. If the given string is greater than a defined length then it will print “The given string exceeds the maximum length” or else the code returns the string.

import java.util.Scanner;

public class Main {
   public static void main(String args[]) {
      int max = 5;
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter String: ");
      String str = scan.next();
      if (str.length() <= max) {
         System.out.println(str);
      } else {
         System.out.println("The given string " +
                   "exceeds the maximum length");
      }
      scan.close();
   }
}

Output:-

Enter String: Java
Java

Enter String: JavaScript
The given string exceeds the maximum length

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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