⬅ Previous Topic
Java StringlastIndexOf()
methodNext Topic ⮕
Java Stringmatches()
methodlength()
method⬅ Previous Topic
Java StringlastIndexOf()
methodNext Topic ⮕
Java Stringmatches()
methodThe length()
method in Java is a fundamental tool for working with strings. It simply tells you how many characters are present within a string. Think of it like counting the letters in your name or words in a sentence – that's essentially what this method does.
public int length()
Parameter | Description |
---|---|
None | This method doesn't accept any input parameters. |
The length()
method returns an integer representing the number of characters in the string.
Let's start with a simple example to illustrate how length()
works. We'll create a string and then use length()
to find out its length.
public class StringLengthExample1 {
public static void main(String[] args) {
String myString = "Hello, World!";
int stringLength = myString.length();
System.out.println("The length of the string is: " + stringLength);
}
}
The length of the string is: 13
In this example, `myString` contains "Hello, World!". The length()
method returns 13 because there are thirteen characters in the string (including the space and the exclamation mark).
What happens when we use length()
on an empty string? Let's find out.
public class StringLengthExample2 {
public static void main(String[] args) {
String emptyString = "";
int length = emptyString.length();
System.out.println("The length of the string is: " + length);
}
}
The length of the string is: 0
As expected, an empty string has a length of zero.
Java strings can contain Unicode characters. Let's see how length()
handles those.
public class StringLengthExample3 {
public static void main(String[] args) {
String unicodeString = "你好世界"; // Chinese for "Hello World"
int length = unicodeString.length();
System.out.println("The length of the string is: " + length);
}
}
The length of the string is: 4
Even though '你好世界' looks like four characters, each character in this string is represented by one code point. The `length()` method returns the number of code points (characters) in the string.
Often you’ll get strings from user input – let's see how to use `length()` with that kind of data.
import java.util.Scanner;
public class StringLengthExample4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String userInput = scanner.nextLine();
int length = userInput.length();
System.out.println("The length of your input is: " + length);
scanner.close();
}
}
This example prompts the user to enter a string, then calculates and prints its length.
⬅ Previous Topic
Java StringlastIndexOf()
methodNext Topic ⮕
Java Stringmatches()
methodYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.