String toString()
时间: 2023-10-20 08:19:04 浏览: 38
The `toString()` method is a method that belongs to the `Object` class in Java. It is used to return a string representation of an object.
When you call `toString()` on an object, the method will return a string that represents the object in a human-readable format. By default, the `toString()` method returns a string that contains the class name of the object, followed by an "@" symbol, and then the object's hash code in hexadecimal format.
For example, consider the following code:
```
Person person = new Person("John", "Doe", 30);
System.out.println(person.toString());
```
Assuming the `Person` class has not overridden the `toString()` method, the output of this code would be:
```
Person@3b6eb2ec
```
However, the `toString()` method can be overridden in a class to provide a more meaningful string representation of an object. For example:
```
public class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
'}';
}
}
```
Now, when you call `toString()` on a `Person` object, you will get a string that contains the person's first name, last name, and age, in a readable format:
```
Person{firstName='John', lastName='Doe', age=30}
```
Note: The `toString()` method is automatically called when you pass an object to the `System.out.println()` method, so you don't need to explicitly call `toString()` in most cases.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)