How to get the length of a string in Java?
In Java, you can use the `length()` method to retrieve the length of a `String` string. Here are the specific steps:
Create a variable of type `String` and assign a value to it. For example:
String str = "Hello, World!";
2. Use the `length()` method to obtain the length of a string. For example:
int length = str.length();
This will return the number of characters in the string `str`.
You can use this variable (`length`) in the code for subsequent operations, such as printing, conditional statements, and so on.
Here is the complete example code:
public class StringLengthExample {public static void main(String[] args) {
String str = "Hello, World!";
int length = str.length();
System.out.println("字符串的长度为:" + length);
}
}
When running the above code, the console will output:
字符串的长度为:13
This shows that the length of the string “Hello, World!” is 13 characters.