Last Updated : 23 Dec, 2024
String length() method in Java returns the length of the string. In this article, we will see how to find the length of a string using the String length() method.
Example:
Java
class Geeks {
public static void main(String[] args){
String s1 = "abcd";
System.out.println(s1.length());
String s2 = "";
System.out.println(s2.length());
String s3 = "a";
System.out.println(s3.length());
}
}
Important Points:
public int length()
Return Type: The return type of the length() method is int.
Examples of Java String length() Method 1. Use of length() method to find size of String Java
public class Geeks {
public static void main(String[] args){
// Here str is a string object
String str = "GeeksforGeeks";
System.out.println(str.length());
}
}
The size of the String is 132. Compare the size of two Strings Java
// whether the length of two strings is
// equal or not using the length() method
import java.io.*;
class Geeks {
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4