How to use toString() method of the Integer class In Java
It is different from method 1 as proposed above, as in this method we use an instance of the Integer class to invoke its toString() method.
Below is the Implementation of the above method:
Java
// Java Program to Illustrate // Integer to String Conversions // Using toString() Method of // Integer Class // Importing required classes import java.util.*; // Main class class GFG { // Main driver method public static void main(String args[]) { // Custom input integer int d = 1234 ; // Converting integer to string // using toString() method of Integer class String str4 = new Integer(d).toString(); // Printing the integer value stored in above string System.out.println( "String str4 = " + str4); } } |
Output
Output explanation: If the variable is of primitive type (int), it is better to use Integer.toString(int) or String.valueOf(int). But if the variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke its toString() method as shown above.
Note: This method is not efficient as an instance of the Integer class is created before conversion is performed.
Java Convert int to String | Different Ways Of Conversion
Converting Integers to Strings involves using the Integer classes toString() or String.valueOf() for direct conversion. String.format() is another method offering flexible formatting options. Using StringBuilder or StringBuffer for appending integer values as strings is efficient for extensive string manipulation.
We generally counter with such conversion articles because many operations can be performed over a string while we are limited to when it comes to integers. We have a wide varied list of in-built methods in the String class that helps us perform hassle-free operations.
Suppose we are required to concatenate two integers then it would become a tedious job as we need to go through as we need to deal with the number system corresponding to which we will be playing mathematics within the number system. But in order to convert integers to strings in Java, we have some inbuilt methods and classes which make our work too easy.
Tip: We generally convert primitive class data members types though we have the concept of Wrapper classes to Strings because in practical programming in java we deal with strings.
Contact Us