This example shows how to convert int to String in Java. This example also shows how to convert int to String using several methods and the best way among them.
How to convert int to String in Java?
There are several ways in which int can be converted to String in Java.
1) Convert int to String using String class
Use valueOf
static method of String class to convert int to String.
1 | static String valueOf(int i) |
valueOf
method returns String representation of int argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package com.javacodeexamples.basic; public class JavaIntToStringExample { public static void main(String args[]){ int i = 10; String strNumber = String.valueOf(i); System.out.println("String value: " + strNumber); } } |
Output
1 | String value: 10 |
2) Convert int to String using Integer wrapper class
Use toString
method of Integer
wrapper class to convert from int to String in Java.
1 | public static String toString(int i) |
This method returns String representation of int value passed as a parameter.
1 2 3 4 | int i = 12345; String strNumber = Integer.toString(i); System.out.println("int to String: " + strNumber); |
Output
1 | int to String: 12345 |
3) Convert int to String using String concatenation
String concatenation can be indirectly used to convert Java primitive values to String as given below.
1 2 3 | int i = 3423; String strNumber = "" + i; System.out.println("String value: " + strNumber); |
Output
1 | String value: 3423 |
What is the best way to convert int to String?
valueOf
method of String class internally calls the toString
method of Integer
wrapper class to convert from int to String value. Using either of the methods is equally efficient in terms of the performance. Preferred way is to use toString
method of Integer
wrapper class.
String concatenation should be avoided mainly for the conversion purpose because,
a) It is difficult to visually understand that the intent of code statement is conversion.
b) String concatenation operation creates unnecessary temporary objects during the conversion process. String concatenation is achieved using StringBuffer
’s or StringBuilder
’s append
method. So the code,
1 | String strNumber = "" + i; |
Will run like,
1 2 3 4 5 6 | StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(i); String strNumber = sb.toString(); |
Please let us know your views in the comments section below.
Add Comment