How to use the toString() in Java

May 10, 2023
How to Use the toString Method in Java



Strings are called ‘special’ by programmers as they protect and prevent our data from manipulation. So, it is natural to side with them whenever possible, and the toString() method in Java enables developers to do just that.

An in-built method, toString(), converts data types such as Integer, Long, Double, and Boolean into strings. Resultingly, we enjoy better functionality, and our codes get glittered with more elements we like.

So, let’s learn how to use this incredible method to write better codes with fewer variables and more strings.

How to use toString() in Java?

Generally, there are two ways to implement the toString() method in Java. The first calls the Java toString() as a function of the object.

class HelloWorld {

    public static void main( String args[] ) {




        // Creating an integer with value 10

        Integer number=10;

        // Calling the toString() method as a function of the Integer

        System.out.println( number.toString() );

    }

}

The second calls the toString() method on Double and returns it as an argument. The trick also functions and works with other data types such as Integer, Long, and Boolean.

class HelloWorld {

    public static void main( String args[] ) {

       

        // The method is called on datatype Double

        // It passes the double value as an argument

        System.out.println(Double.toString(11.0));

        // Implementing this on integer, long, and Boolean

        //Integer

        System.out.println(Integer.toString(12));


        // Long

        System.out.println(Long.toString(123456789));


        // Booleam

        System.out.println(Boolean.toString(false));

    }

}

More interestingly, programmers can also override the toString() method in Java as a class for added functionality and ease of use.

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("Doug",9);

      //Calling the class version of toString()

        System.out.println(p.toString());

      //Calling the original toString()

      System.out.println(Integer.toString(12));

    }

}
The name of the pet is Doug. The age of the pet is 9.

12

Classes with default Java toString()

Some classes in Java come with pre-implemented Java toString(). They show objects as strings and come naturally overridden by their string counterparts. These include Wrapper classes like Integer, Byte, Float, Boolean, Character, and Double, and Collection classes like StringBuilder, String, and StringBuffer.

Example:

import java.util.*;

public class Main {

  public static void main(String[] args) {

    Integer integer = 27;

    String name = "Jordan";

    List<String> cities = new ArrayList<>();

    cities.add("New York");

    cities.add("Chicago");

    cities.add("Philadelphia");

    System.out.println(integer);

    System.out.println(name);

    System.out.println(cities);

  }

}

Output:

In the example above, it is clear how System.out.println() automatically prints the string values without writing a separate command.

Implementing Static toString() in Wrapper Classes

Wrapper classes also statically implement the toString() method, which enables us to get the string values directly without defining the class object.

Example:

public class Main {

  public static void main(String[] args) {

    String representation = Integer.toString(34);

    System.out.println(representation);

  }

}

Output:

34

Using valueOf() Method

String.valueOf() is another way to represent objects as strings automatically or internally.

Example:

public class Main {

  public static void main(String[] args) {

    String representation = String.valueOf(6.8);

    System.out.println(representation);

  }

}

Output:

6.8

When to use the Java toString() Method?

A developer has to create numerous user-defined classes to implement modifications and write complex codes. For simplicity, Java provides standard libraries, further classified into packages, with built-in interfaces, methods, and classes. They help developers effectively write codes, manage workload, and keep repetitive codes at a minimum.

A toString() in Java is one such method in the Object class. While working with objects, implementing Java toString() enables us to convert objects or arguments into strings and deploy codes faster and with less hassle.

Knowing methods like Java toString() gives developers much-needed headspace and bandwidth to invest in writing better codes.

The Final Word

The toString() method in Java represents objects like integers, long, double, and Boolean as strings. Some classes in Java come naturally overridden with toString() and have their unique implementation of the feature. Generally, there are two main implementations of toString() in Java.

The first uses object or data types, while the second works with arguments. Both offer similar functionality and return or convert the input into a more desirable string format.

Also Read: Java String Substring() Method with Examples



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US