In the post converting String to int we have already seen ways to convert string to int in Java, this post is about doing just the reverse; convert int to string in Java.
Concatenating with an empty String
Easiest way to convert an int to a string in Java is to concatenate int with an empty string. That will give you a string value, conversion is handled for you.
public class IntToString { public static void main(String[] args) { int num = 7; String value = "" + num; System.out.println("Value is " + value); } }
Output
Value is 7
Convert int to string in Java using valueOf() method
String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. You can use valueOf(int i) method to convert int to String by passing int value as an argument to the method which returns the string representation of the int argument.
public class IntToString { public static void main(String[] args) { int num = 7; String value = String.valueOf(num); System.out.println("Value is " + value); } }
Output
Value is 7
Conversion of int to String using toString() method
Each of the Number subclasses (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. You can use use Integer.toString(int i) method of the Integer wrapper class to convert int to String in Java. The method returns a String object representing the passed integer.
public class IntToString { public static void main(String[] args) { int num = 7; String value = Integer.toString(num); System.out.println("Value is " + value); } }
Output
Value is 7
That's all for this topic Convert int to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment