This example shows how to convert int to string in Java using toString, valueOf, and + operator. It also shows the best way to convert int to string.
How to convert int to String in Java?
1) Convert int to String using String class
Use the valueOf
static method of the String class to convert.
1 |
static String valueOf(int i) |
The valueOf
method returns a 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) Using the Integer wrapper class
Use the toString
method of the Integer wrapper class to convert.
1 |
public static String toString(int i) |
This method returns a string representation of an 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) Using String concatenation
String concatenation can be indirectly used to convert any Java primitive value to a 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?
The valueOf
method of the String class internally calls the toString
method of the Integer wrapper class to convert from int to a string value. Using either of the methods is equally efficient in terms of performance. The preferred way is to use the toString
method of the 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 the code statement is conversion.
b) String concatenation operation creates unnecessary temporary objects during the conversion process. String concatenation is achieved using the append
method of the StringBuilder or StringBuffer class. 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(); |
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.