Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well.
The String class of Java comprises a lot of methods to execute various operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring(), etc. Out of these methods, we will be focusing on the Java String class length() method.
How to Find Length of String in Java
The string length or size means the total number of characters present in it. In String, all the elements are stored in the form of characters i.e., “1”, ” “, “_”, etc all are considered as characters.
For Example:
String: "Geeks For Geeks" size: 15
String.length() method
The Java String length() method is a method that is applicable to string objects. The length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays.
The length() method can also be used for StringBuilder and StringBuffer classes. The length() method is a public member method. Any object of the String class, StringBuilder class, and StringBuffer class can access the length() method using the ( . ) dot operator.
Method Signature
The method signature of the length() method is as follows:
public int length()
Return Type
- The return type of the length() method is int.
Examples of Java String length() method
The following examples demonstrate the use of the Java String length() method.
1. Use of length() method to find size of String
Java program to demonstrate how to get the length of a String in Java using the length() method
Java
// Java program to illustrate // how to get the length of String // in Java using length() method // Driver Class public class Test { // main function public static void main(String[] args) { // Here str is a string object String str = "Lazyroar" ; System.out.println( "The size of " + "the String is " + str.length()); } } |
The size of the String is 13
2. Compare the size of two Strings
Java program to illustrate how to check whether the length of two strings is equal or not using the length() method.
Java
// Java program to illustrate how to check // whether the length of two strings is // equal or not using the length() method. import java.io.*; // Driver Class class GFG { // main function public static void main(String[] args) { String s1 = "abc" ; String s2 = "xyz" ; // storing the length of both the // strings in int variables int len1 = s1.length(); int len2 = s2.length(); // checking whether the length of // the strings is equal or not if (len1 == len2) { System.out.println( "The length of both the strings are equal and is " + len1); } else { System.out.println( "The length of both the strings are not equal" ); } } } |
The length of both the strings are equal and is 3