Why Use toString()?
The toString() method in Java is used to convert an object into a readable string format. This is helpful because it allows developers to understand what an object contains easily. It's especially useful in debugging, where it shows the internal state of objects, and in logging, to record meaningful data in logs. In user interfaces or the console, toString() helps display information clearly. Java automatically calls toString() when an object is printed with System.out.println(), making it a common and convenient way to inspect objects during development.
Example:
class Person {
String name = "Rahul";
int age = 25;
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
// toString() is called automatically
System.out.println(p);
}
}

You can also try this code with Online Java Compiler
Run CodeReturn Value:
In the integer class, toString Java is used to return a string object representing an Integer object. The three different types toString() are as follows:
- toString()
The toString() Java method is used to return an equivalent string to the integer value.
- toString(int i)
The toString(int i) method is inbuilt in Java. It is used to return string objects representing a distinct integer from the method argument.
- toString(int i, int radix)
The last toString Javan method in Integer Class is the toString(int i, int radix), which returns a string expression of the first int type in the radix determined by the second argument.
Whereas in the object class,toStringJava is used to return a string representation of the object. In simple words, it returns the string, which textually depicts the objects.
In this type, the toString method is invoked internally whenever the object reference is printed. If the toStrig method is not defined in the class, then the toString in Object Class is invoked.
Also see, Duck Number in Java and Hashcode Method in Java.
Syntax of toString
Here are the syntax for toString Java in the Integer class:
public String toString()
public static String toString(int i)
public static String toString(int i, int radix)
In the above syntax,
- The toString accepts no parameters and returns the string representation of the integer in the base of 10.
- The toString(i) accepts parameters. It is a user-specified value which is to be converted to a string and returns the representation in an int-type argument in the base of 10.
- Whereas the toString(radix) also requires a parameter but it is used to convert the string object. It reruns the string representation in the int type argument of the specified radix.
And for the toString Java Object Class:
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
In the above syntax, the toString() does not take any parameter.
But it is important to note that the class name, @, and the unsigned hexadecimal representation of the object's hash code is the default way of printing.
Also see, Swap Function in Java
Implementation without toString() Method in Java
Java
class Vehicle {
String name;
Integer cost;
Vehicle(String name, Integer cost) {
this.name = name;
this.cost = cost;
}
}
public class Main {
public static void main(String args[]) {
Vehicle v1 = new Vehicle("SUV", 1700000-800000);
Vehicle v2 = new Vehicle("Hatchback",1200000 - 500000);
//'system.out.println' invokes the toString() method internally for printing,
System.out.println("v1:- " + v1);
System.out.println("v2:- " + v2);
// toString() converts the integer object to String
System.out.println(v1.cost.toString()+" <- cost");
System.out.println(Integer.toString(v1.cost)+" <- cost");
}
}

You can also try this code with Online Java Compiler
Run Code
Output
v1:- Vehicle@1dbd16a6
v2:- Vehicle@251a69d7
900000 <- cost
700000 <- cost
Explanation
In this program, the Hex Codes of the values are printed as the string representation of vehicles 1 and 2. But, for a better understanding, we need to print the values of the objects. Let us tune our approach in the following program called the Overriding method or the Default Implementation of toString Java.
Example of toString() Method in Java
Java
class Vehicle {
String name;
Integer cost;
Vehicle(String name, Integer cost) {
this.name = name;
this.cost = cost;
}
@Override
public String toString() {
return "Vehicle{" + "'" + name + '\'' + ", costs around: " + cost + '}';
}
}
public class Main {
public static void main(String args[]) {
Vehicle v1 = new Vehicle("SUV", 1000000);
System.out.println("v1: " + v1);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
v1: Vehicle{'SUV', costs around: 1000000}
Explanation
In the above implementation, overriding is required to return the user-specified values.
Overriding brings out helpful information about the class object as compared to hex codes.
Note: The user does not extend the Object. This is the job of the Java compiler. The compiler checks for the method toString() and summons the implementations required; default or overridden.
Time Complexity
The time complexity of the program in O(1). This means that a constant time is taken, regardless of the input size. Object and String are independent of input size.
Space Complexity
The space complexity of the program is O(n). The size of the class ‘Vehicle’ requires some memory to store two variables ‘name’ and ‘cost’. The size of these inputs depends upon the input value and their data type.
Advantage of toString() Java
- The toString method is a standard way to represent strings. In Java, a human-readable format of objects is not provided. This is where the toString() method comes in handy.
- The code readability and complexity are reduced. This is because by overriding the toString Java of the Object class, we can return the values of the Object.
- The toString method is defined in the Object class, which is the “superclass” of all the classes present in Java. Hence, every object inherits all the methods from the Object class, which is the default way to implement the string representation.
Disadvantages of toString() in Java
- Default Implementation is Uninformative
If you don’t override toString(), Java uses the default method from the Object class, which returns the class name followed by a hashcode (e.g., MyClass@1a2b3c). This doesn't give any useful information about the object’s actual data. - Security/Privacy Risk
If toString() is not carefully written, it may expose sensitive information like passwords or personal data when logging or displaying objects.
Example:
class User {
String username = "rahul_sharma";
String password = "secret123";
}
public class Main {
public static void main(String[] args) {
User u = new User();
System.out.println(u); // Output: User@15db9742 (default toString)
}
}

You can also try this code with Online Java Compiler
Run CodeImproved Version:
public String toString() {
return "User[username=" + username + "]";
}
Real-Life Use Cases of toString() in Java
- Logging Object States
In real-world applications, developers use toString() to log object details for monitoring or debugging. It helps track how data flows or changes over time, especially in large systems or microservices. - Displaying Readable Outputs
In user interfaces (UI), command-line tools, or reports, toString() provides clean and meaningful object data, making the output easy to read and understand without diving into code or internal structures. - Debugging Complex Structures
When troubleshooting errors, toString() lets developers inspect object states quickly. Overridden methods show the exact data within objects, helping to spot bugs or misbehaviors faster during development or testing.
Frequently Asked Questions
What does Java toString () equal?
Java toString() returns a string representation of an object. It's often overridden to provide meaningful information about the object's state.
Where is toString () defined?
The toString() is defined in the Object class, the root class for all Java objects, and can be overridden in derived classes.
Is toString a static method?
No, toString() is an instance method. Each object has its own implementation, allowing it to provide custom string representations.
What is toString in object class?
In the Object class, toString() returns a string containing the class name along with the object's hash code, unless overridden for specific behavior.
Conclusion
In this article, we covered tostring in Java.
Hope this article helped you in your learning journey.
Recommended Readings: