Friday, 9 September 2016

Converting int to string - Java Program

In the post converting String to int we have already seen ways to convert string to int, this post is about doing just the reverse; convert integer values to string.

Concatenating with an empty String

Easiest way to convert an int to a string 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

Using valueOf() method of String class

String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. Using valueOf(int i) method will return 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

toString() method of the wrapper classes

Each of the Number subclasses (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. Thus, using Integer.toString(int i) returns a String object representing the specified 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 Converting int to string - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to find all the permutations of the given String
  2. How to find the longest palindrome in the given String
  3. How to add double quotes to a String
  4. Java String interview questions

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment