Tutorial Playlist
The toString() method in Java is a pre-existing method found in the Object class. It serves the purpose of returning a string representation of an object. By default, it produces a string comprising the object's class name, followed by an "@" symbol and hash code.
This method can be customized in user-defined classes to generate a more descriptive string representation. This proves valuable in scenarios such as debugging, logging, or presenting object details in a readable manner.
In this tutorial, you will learn about the basics of the toString() method in Java, including what it does and why it is important in programming. This will serve as an in-detail guide to explain how to override the toString() technique in user-defined classes to customize the string representation of objects. Read on to gain a solid base in the toString() method and its role in Java development.
The toString() method in Java is a pre-defined method in the Object class. It serves as the base class for all Java classes. It is used to retrieve a string representation of an object.
Nevertheless, developers can override this method in their own classes to provide a customized string representation. This allows for tailored object representations, facilitating debugging, logging, and displaying object information. Moreover, the toString() method is extensively employed in Java APIs and frameworks for converting objects to strings for various purposes.
The toString() method in Java obtains a string representation of an object. It returns a string that represents the object's state or contents. Its default implementation returns a string representation that includes the class name, an ‘@‘ symbol, and the object's memory address.
Here is the syntax for the toString() method:
@Override
public String toString() {
// Generate the string representation of the object
// Return the generated string
}
To override the toString() method in a class, you must include the @Override annotation to ensure that you correctly override the method from the superclass. Within the method body, you generate the string representation of the object based on its state and return the generated string.
Here's an example of how to use the toString() method:
In the above example, the Person class overrides the toString() method to provide a string representation of a Person object. The toString() method returns a string that includes the name and age of the person.
When the toString() method is called on a Person object, it returns the generated string representation, which is then printed using System.out.println() in the main() method.
Code:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
public static void main(String[] args) {
Person person = new Person("John Doe", 25);
System.out.println(person.toString());
}
}
The Java toString() method offers several benefits:
When the toString() method in Java is not overridden, the default implementation provided by the Object class is utilized. However, relying on the default toString() method can be problematic as it may not offer a clear understanding of the object's state or contents. This can pose challenges when attempting to debug or log information about the object during runtime.
Furthermore, in scenarios where APIs or frameworks rely on the toString() method, the lack of a customized implementation can result in less useful output. This can hinder the interpretation and utilization of objects within these contexts.
To address these issues, it is recommended to override the toString() method in Java classes and provide a customized implementation that provides a more meaningful representation of the object's state. This facilitates easier debugging, logging, and integration with other Java components.
In this example, the Book class represents a book with a title, author, and publication year. The toString() method is overridden to provide a custom string representation of the Book object. It generates a string that includes the title, author, and year.
In the main method, a Book object named book is created with the title "The Great Gatsby", author "F. Scott Fitzgerald", and year 1925. The toString() method is then called on the book object, and the resulting string representation is printed using System.out.println().
Code:
public class Book {
private String title;
private String author;
private int year;
public Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", year=" + year +
'}';
}
public static void main(String[] args) {
Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
System.out.println(book.toString());
}
}
In this example, the toString() method is invoked on an array of integers (numbers). By default, the toString() method inherited from the Object class is called, which returns a string representation of the array's memory address.
public class upGradTutorials {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.toString());
}
}
The above code declares an array of integers named numbers and initializes it with values. The toString() method is then invoked on the numbers array. By default, the toString() method inherited from the Object class is called, which returns a string representation of the array's memory address. The result is printed using System.out.println().
In this example, the toString() method is invoked on an ArithmeticException object, which is thrown when dividing by zero. The toString() method provides information about the exception, including the exception class name and a message.
public class upGradTutorials {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(e.toString());
}
}
}
The code demonstrates exception handling for an arithmetic operation that causes a divide-by-zero error. An arithmetic operation is performed inside a try-catch block where 10 is divided by 0. This operation throws an ArithmeticException.
The exception is caught using a catch block that specifies ArithmeticException. Inside the catch block, the toString() method is called on the exception object (e) to get a string representation of the exception. The resulting string, which contains the exception class name and a message, is printed.
In this example, the toString() method is overridden in the Vehicle class to provide a custom string representation of the object. The method returns a string that includes the vehicle's make, model, and year.
public class Vehicle {
private String make;
private String model;
private int year;
public Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
@Override
public String toString() {
return "Vehicle{" +
"make='" + make + '\'' +
", model='" + model + '\'' +
", year=" + year +
'}';
}
public static void main(String[] args) {
Vehicle vehicle = new Vehicle("Toyota", "Camry", 2022);
System.out.println(vehicle.toString());
}
}
The above example defines a class named Vehicle with private variables make, model, and year. The class has a constructor to initialize these variables. The toString() method is overridden with a custom implementation that returns a string representation of the object. The method concatenates the values of make, model, and year with additional text for clarity.
In the main() method, a Vehicle object is created and assigned values. The toString() method is called on the object, and the resulting string representation is printed.
Understanding the toString() method in Java is crucial for obtaining a meaningful string representation of objects. By customizing the toString() method, developers can enhance their Java applications' debugging, logging, and integration capabilities.
Enrolling in a course from upGrad can be highly beneficial for a comprehensive understanding of Java and its various features, including the toString() method. upGrad offers industry-relevant courses taught by experienced instructors, providing a structured learning path and hands-on projects to strengthen your Java skills.
1. Is toString() a pre-existing function in Java?
Yes. The toString method is a default method in the Object class in Java.
2. Is toString() used to display a string?
The toString() method in Java returns a string representation of an object rather than modifying the original string itself. The toString() method provides a way to obtain a string representation of an object's state or contents, which can be helpful for various purposes, such as debugging, logging, or displaying information.
3. What is the opposite of the toString() method?
The toString() method, when used with a number, allows for the conversion of a decimal number into various number systems ranging from 2 to 36.
PAVAN VADAPALLI
popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .