Intern
What does the toString() method do?
sobes.tech AI
Answer from AI
The toString() method provides a string representation of an object. It is commonly used for debugging or logging to obtain information about the object's state in a human-readable format.
In most programming languages, base classes have a standard implementation of toString(), but it is recommended to override it in custom classes to provide more meaningful information.
Example of overriding in Java:
// User class
class User {
private String name;
private int age;
// Constructor
public User(String name, int age) {
this.name = name;
this.age = age;
}
// Override toString method
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// Main method for usage example
public static void main(String[] args) {
User user = new User("Alice", 30);
System.out.println(user); // Prints the string from toString
}
}
Example of overriding in Python:
# User class
class User:
# Constructor
def __init__(self, name, age):
self.name = name
self.age = age
# Override __str__ method (analogous to toString in Python)
def __str__(self):
return f"User{{name='{self.name}', age={self.age}}}"
# Override __repr__ method (developer representation)
def __repr__(self):
return f"User(name='{self.name}', age={self.age})"
# Usage example
user = User("Bob", 25)
print(user) # Prints string from __str__
print(repr(user)) # Prints string from __repr__
In JavaScript:
// User class
class User {
// Constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
// Override toString method
toString() {
return `User{name='${this.name}', age=${this.age}}`;
}
}
// Usage example
const user = new User("Charlie", 35);
console.log(user.toString()); // Calls toString explicitly
console.log(user); // May call toString automatically in browser console
Main purposes of toString():
- Debugging: Quickly see the contents of an object.
- Logging: Simplifies recording object information in log files.
- String conversion: Used when an object needs a string representation (e.g., in string concatenation).