Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

toString Method in Java – How to Use It (with Examples)

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

The ‘toString’ method in Java is essential to the Java programming language. It is widely used for converting objects into a string representation. The ‘toString’ method is defined in the Object class. The Object class is the superclass of all the sub-classes, meaning every object in Java has access to the ‘toString’ method. This article explained the toString method.

What is toString() Method in Java

The toString() method is the built-in method in Java. That provides a string representation of an object. The toString() method is quite useful in that it allows string representations of objects. It can be useful during debugging, logging, and displaying information about the objects as human-readable text.

 

The following program demonstrates the toString() method:

 

Program

class Account { private String accountHolderName; private int accountNumber; private double balance; public Account(String accountHolderName, int i, double balance) { this.accountHolderName = accountHolderName; this.accountNumber = i; this.balance = balance; } @Override public String toString() { return "Account{" + "Account Holder: '" + accountHolderName + ''' + ", Account Number: '" + accountNumber + ''' + ", Balance: $" + balance + '}'; } } class Main{ public static void main(String args[ ]){ Account ob = new Account("Neeraj Kumar",33435 , 159.5) ; System.out.println(ob.toString()); } }

Output

Account{Account Holder: 'Neeraj Kumar', Account Number: '33435', Balance: $159.5}

Override the toString() method in Java

Overriding the ‘toString()’ method in Java allows you to define a custom string representation for an object. The detailed explanation and example of “how to override the ‘toString()’ method in Java.

The following program demonstrates the toString() method:

 

Program:

class Student { String name ; int age ; Student(String name, int age){ this.name = name ; this.age = age ; } public String toString(){ return "Student{" + "Name ='" + name + ''' + ", Age=" + age + '}'; } }   class Main{ public static void main(String args[]){ Student ob = new Student("Anupriya", 23) ; System.out.println("Output"+ob) ; } }

Output  

OutputStudent{Name ='Anupriya', Age=23}

Java Classes with toString() Overridden by Default

toString Method in Java

 

In Java, All the wrapper classes like Byte, Integer, Long, Float, Double, Boolean, and Character have overridden the toString() method. The collection classes, such as String and StringBulder, have also overridden the toString() method.

 

Source Code:

import java.util.*; class Main{ public static void main(String args[]){ System.out.println(" toString Method Example in Java "); Integer integer = 55 ; String name = "Neeraj Kumar" ; List<String> cities = new ArrayList<>() ; cities.add("France") ; cities.add("Kolkata") ; cities.add("Mumbai Watermellon") ; System.out.println(integer); System.out.println(name) ; System.out.println(cities) ; // System.out.println() method by default uses toString() method internally } }

Output

55 Neeraj Kumar [France, Kolkata, Mumbai Watermellon]
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Using static toString() method in Wrapper Classes

The Wrapper classes in Java implement the ‘toString()’ method statically. We can directly get the String value without defining an object of the class.

 

The following program demonstrates the toString() method:

 

Program

public class Main { public static void main(String args[]){ String representation = Integer.toString(3344) ; System.out.println(representation); System.out.println(representation.getClass());  } }

Output

3344 class java.lang.String

Using valueOf() Method in String Class

The valueOf() method in the ‘String’ class is a versatile utility in Java that converts different data types into their corresponding ‘String’ representation. This method is particularly useful when converting primitive data types, objects, or arrays into a ‘String’.

 

The following program demonstrates the valueOf() method in Java:

class Main{ public static void main(String args[]){ String representation = String.valueOf(533.3) ; System.out.println(representation); } }

Output

533.3

Best Practices for Overriding ‘toString()’

Let’s see some best practices for overriding the method.

 

  • Keep it Simple: The string method should be simple and informative. That must include only the essential information that defines the object.
  • Avoid Sensitive Information: Developers must not include sensitive data like passwords or personal information.
  • Use StringBuilder: It performs better, especially when concatenating multiple strings. Use ‘StringBuilder’ instead of ‘+’ for string concatenation.
  • Ensure Readability: The output of the ‘toString()’ method should be easily readable and understandable to the person who will see it.
  • Improved Readability: For complex objects, especially in large applications, a well-defined ‘toString()’ method helps make the output more human readable. This is particularly useful for developers who are working with or maintaining the source code.

Conclusion

 

Java’s ‘toString()’ method is fundamental for converting objects into a human-readable string format. By overriding this method, you can customize how objects are represented as strings, enhancing the clarity and usefulness of the output whether working with custom classes, wrapper classes, or using the ‘valueOf()’ method in the ‘String’ class, understanding and effectively implementing ‘toString()’ will improve your code’s readability and debugging process.

FAQs
The ‘toString()’ method can significantly aid debugging by providing clear and concise information about the state of objects in log messages or during exception handling.
No, ‘toString()’ is an instance method, meaning it operates on an instance of a class. It cannot be used in static contexts where there is no instance on which to operate.
Yes, We can use the ‘toString()’ method that is often used for logging purposes. It provides a convenient way to include object states in log messages. It makes it easier to trace and debug issues.
Yes, we can include the values of instance variables in the ‘toString()’ method to provide detailed information about the object’s state.  
The ‘toString()’ method does not affect object equality. Object equality is determined by the ‘equals()’ method, while ‘toString()’ is solely for generating string representation of objects.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved