Home >Java >javaTutorial >How to get the string representation of a number using toString() method in Java?

How to get the string representation of a number using toString() method in Java?

WBOY
WBOYforward
2023-08-20 22:37:431159browse

How to get the string representation of a number using toString() method in Java?

The toString() method is an important method of the Object class, which can be used to return a string or text representation of the object. The toString() method of the object class returns a string, which is the class name of the specified object, followed by the "@" symbol and the hash code of the object (java.lang.String;@36f72f09)

We can also use the toString() method to get the string representation of a number, which is useful if the string consists of numbers in different variables. In this case, the numbers can be converted to strings and concatenated to create a combined or formatted string.

Grammar

public String toString()

Example

is translated as:

Example

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);
<strong>      </strong>//converting numbers to string format by toString()<strong>
</strong>      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);
   }  
}

Output

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

The above is the detailed content of How to get the string representation of a number using toString() method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete