Trusted answers to developer questions

How to use the toString() in Java

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

How to use the toString() method

The toString() method in Java has two implementations;

  1. The first implementation is when it is called as a method of an object instance. The example below shows this implementation
class HelloWorld {
public static void main( String args[] ) {
//Creating an integer of value 10
Integer number=10;
// Calling the toString() method as a function of the Integer variable
System.out.println( number.toString() );
}
}
  1. The second implementation involves calling a method from the relevant class and passing the value as an argument. The example below demonstrates this:

class HelloWorld {
public static void main( String args[] ) {
// The method is called on datatype Double
// It is passed the double value as an argument
System.out.println(Double.toString(11.0));
// Implementing this on other datatypes
//Integer
System.out.println(Integer.toString(12));
// Long
System.out.println(Long.toString(123213123));
// Boolean
System.out.println(Boolean.toString(false));
}
}

Overriding the toString() method

What is interesting is that this method can also be over-ridden as part of a class to cater to the customized needs of the user. The example below shows how to do this!

class Pet{
String name;
Integer age;
Pet(String n, Integer a){
this.name=n;
this.age=a;
}
//Over-riding the toString() function as a class function
public String toString(){
return "The name of the pet is " + this.name + ". The age of the pet is " + this.age;
}
}
class HelloWorld {
public static void main( String args[] ) {
Pet p = new Pet("Jane",10);
//Calling the class version of toString()
System.out.println(p.toString());
//Calling the original toString()
System.out.println(Integer.toString(12));
}
}

In the code above, from lines 11 to 13 we have simply created a new method within the Pet class with the same name as the toString() method. On line 20 when the toString() method is called, it is the class version of the method that is invoked. However as seen on line 22, the method does not change for any other data type!

RELATED TAGS

tostring
java
convert to string
string conversion
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?