Sunday, June 13, 2021

Convert int to String in Java

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

  1. Convert float to int in Java
  2. Arrange Non-Negative Integers to Form Largest Number - Java Program
  3. Find All Permutations of a Given String Java Program
  4. Java Program to Find The Longest Palindrome in a Given String
  5. Java String Interview Questions And Answers

You may also like-

  1. How to Find Common Elements Between Two Arrays Java Program
  2. How to Display Time in AM-PM Format in Java
  3. How to Count Lines in a File in Java
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. Ternary Operator in Java With Examples
  6. How HashSet Works Internally in Java
  7. ConcurrentHashMap in Java With Examples
  8. Deadlock in Java Multi-Threading

No comments:

Post a Comment