String Length() Method in Java: How to find with Example

What is String “Length” Method in Java?

This function is used to get the length of string in Java. The string length method returns the number of characters written in the String. This method returns the length of any string which is equal to the number of 16-bit Unicode characters in the string.

String “Length” Method Syntax:

public int length()

Parameters:

NA

Return Value:

This method returns the length of a string in Java.

Java string Length Method Examples:

In this program, we will learn how to find the length of a string in Java. We have two Strings and we will find out string length in Java using length() method.

public class Sample_String {
    public static void main(String[] args) {
        //declare the String as an object S1 S2
        String S1 = "Hello Java String Method";
        String S2 = "RockStar";

        //length() method of String returns the length of a String S1.
        int length = S1.length();
        System.out.println("Length of a String is: " + length);
        //8 Length of a String RockStar
        System.out.println("Length of a String is: " + S2.length());
    }
}

Output:

Length of a String is: 24

Length of a String is: 8