The length() method in Java returns the number of characters present in a String object. This includes all characters (letters, numbers, spaces, punctuation, etc.), but does not count the null terminator as Java strings are not null-terminated like in some other languages (e.g., C/C++). The index of the string starts at 0, but the length() method returns a count of characters, not the index.
The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here:
Syntax:
int length()
Return Type:
The method returns an int representing the number of characters in the string.
Example:
public class StringLengthExample {
public static void main(String[] args) {
// Create a string
String str = "Hello, World!";
// Using length() to get the number of characters in the string
int length = str.length();
// Print the length
System.out.println("The length of the string is: " + length); // Output: 13
}
}
Explanation:
- The string “Hello, World!” consists of 13 characters, including the comma and space.
- The length() method returns 13, which is the total number of characters in the string.
If the string is empty
If the string is empty (i.e., it contains no characters), the length() method will return 0.
public class EmptyStringExample {
public static void main(String[] args) {
// Create an empty string
String emptyStr = "";
// Using length() to get the number of characters in the empty string
int length = emptyStr.length();
// Print the length
System.out.println("The length of the empty string is: " + length); // Output: 0
}
}
Explanation:
The empty string “” has no characters, so length() returns 0.
Java String length() Method – Interview Questions
Q 1: Java String length() Method
Q 2: What is the return type of length()?
Q 3: Does length() count spaces?
Q 4: Can length() return zero?
Q 5: Is length() a property or method?
Java String length() Method – Objective Questions (MCQs)
Q1. The length() method in Java returns:
Q2. What will be the output of the following code?
String s = "Hello";
System.out.println(s.length());
Q3. Which of the following is the correct syntax for using the length() method?
Q4. What is the return type of length() method in Java String class?
Q5. What will System.out.println("Java ".length()); display?