There are many operations which can be performed on a string but not on an integer. For example, concatenation, finding a substring, etc.
Now suppose we want to concatenate two integers or find out if an integer contains a digit; this would be a hassle if we are to only use numerical operations. However, converting an integer to a string will make things easier.
This method is present in many Java classes. It returns a string. You can use it as a static function of the Integer class like this:
Integer.toString(123)
Or, use the normal version of the Integer class’ object. This cannot be used with the primitive type int, so remember to convert it to an Integer first by passing it to the constructor or simple assignment using ‘=’ operator (see the example below) :
Integer i = 123;
i.toString();
To check the type of variable, use the
getClass().getName()
method.
public class main{public static void main(String[] args){// Converting 'int' to 'Integer'int x = 123;Integer y = new Integer(x); // passing to constructor// Integer y = x; // or use simple assignmentSystem.out.println("Before conversion: " + y.getClass().getName());System.out.println("After conversion: " + y.toString().getClass().getName());System.out.println("After conversion (using Static method): " + Integer.toString(x).getClass().getName());}}
Pass your integer (as an int or Integer) to this method and it will return a string:
String.valueOf(Integer(123));
public class main{public static void main(String[] args){Integer i = new Integer(123);System.out.println("Before conversion: " + i.getClass().getName());System.out.println("After conversion: " + String.valueOf(i).getClass().getName());}}
These two classes build a string by the append()
method. We create an object of one of these two classes and call this method by passing our integer:
public class main{public static void main(String[] args){Integer i = new Integer(123);StringBuilder sb = new StringBuilder(); // or StringBuffersb.append(i);System.out.println(sb);}}
The first argument is any string containing %d. The second argument is the integer you want to convert. This method will replace %d with your integer. This method is not solely meant for the purpose of conversion:
String.format("%d", 100);
public class main{public static void main(String[] args){Integer i = new Integer(123);System.out.println("Before conversion: " + i.getClass().getName());System.out.println("After conversion: " + String.format("%d", i).getClass().getName());}}
Concatenation is also not meant for conversion, but you can concatenate your integer to an empty string because when you add an integer to a string, the result is a string:
String str = "" + 123;
public class main{public static void main(String[] args){Integer i = new Integer(123);System.out.println("Before conversion: " + i.getClass().getName());System.out.println("After conversion: " + ("" + i).getClass().getName());}}
Free Resources