How to get the string representation of numbers using toString() in Java?

JavaObject Oriented ProgrammingProgramming

The toString() method is an important method of Object class and it can be used to return the string or textual representation of an object. The object class’s toString() method returns a string as the name of the specified object’s class which is followed by ‘@’ sign and the hashcode of the object (java.lang.String;@36f72f09)

We can use the toString() method to get the string representation of numbers as well and it can be useful if the string consists of numbers taken from different variables. In that case, the number can be converted to a string and concatenate to create a combined or formatted string.


public String toString()


public class ToStringMethodTest {
   public static void main(String args[]) {
      int num1 = 50;
      Integer num2 = 75;
      float flt1 = 50.75f;
      Float flt2 = 80.55f;
      double dbl1 = 3256522.44d;
      Double dbl2 = new Double(565856585d);
      //converting numbers to string format by toString()
      String str_int1 = Integer.toString(num1);
      String str_int2 = num2.toString();
      String str_flt1 = Float.toString(flt1);
      String str_flt2 = flt2.toString();
      String str_dbl1 = Double.toString(dbl1);
      String str_dbl2 = dbl2.toString();
      System.out.println("int to string = " + str_int1);
      System.out.println("Integer to string = " + str_int2);
      System.out.println("float to string = " + str_flt1);
      System.out.println("Float to string = " + str_flt2);
      System.out.println("double to string = " + str_dbl1);
      System.out.println("Double to string = " + str_dbl2);


int to string = 50
Integer to string = 75
float to string = 50.75
Float to string = 80.55
double to string = 3256522.44
Double to string = 5.65856585E8
Published on 26-Aug-2019 08:20:30