Java String length Method

The Java String length Method is to find and return the length of the User specified string. The length is equal to the number of Unicode units in a string. In this article, we will show how to find the length of a String using the Java string length method with an example. The basic syntax of the String length in Java Programming language is as shown below.

public int length() // It will return the integer Value as Output

//In order to use in program
String_Object.length()
  • String_Object: Please specify the valid String Object to find its length.

Java String length example

The String length method returns the length of the user-specified string. In this program, we are going to declare a few string objects and then find the length of those strings using this String function.

//How to find Length using Java String.length method
package StringFunctions;

public class StringLength {
	public static void main(String[] args) {
		String str = "Hello";
		int str1 = str.length();
		String str2 = "Tutorial GateWay";
		String str3 = "Free Java Tutorial at Tutorial GateWay";
		String str4 = "Java Programming Language";
		
		System.out.println("The Length of a String Str = " + str1);
		System.out.println("The Length of a String Str2 = " + str2.length());
		System.out.println("The Length of a String Str3 = " + str3.length());
		System.out.println("The Length of a String Str4 = " + str4.length());
	}
}
Java String length Method 1

In this string length example, First, we declared the String variable and assigned a value using the following statement

String str = "Hello";

The following String function statement will find the length of the above-specified string. Here we are assigning the output to integer values because string length in java returns an integer value.

int str1 = str.length();

Next, we declared three more strings using the following Java statements

String str2 = "Tutorial GateWay";
String str3 = "Free Java Tutorial at Tutorial GateWay";
String str4 = "Java Programming Language";

The following System.out.println statements will call the public int length() method to find the string length and then print the output

System.out.println("The Length of a String Str2 = " + str2.length());
System.out.println("The Length of a String Str3 = " + str3.length());
System.out.println("The Length of a String Str4 = " + str4.length());