PUBLISHED ON: JANUARY 22, 2021
How to Convert Int to String in Java
In this post, we are going to convert int type to string in Java. An integer is a data type that holds floating-point values whereas String is a sequence of characters and a class in Java.
To convert int to String there are several ways like the valueOf()
method of String class or toString()
method of Integer class or a simple string literal that converts an expression to string.
The valueOf()
method belongs to String that returns a string of the specified value and The toString() method of Integer class returns a string of the floating-point value.
Here, we are going to see all these conversions with the help of several examples.
Time for an Example:
Let's create an example to convert an int type to a string. Here, we are using valueOf()
method that returns a string from the specified value.
public class Main {
public static void main(String[] args){
int val = 10;
System.out.println(val);
// int to String
String str = String.valueOf(val);
System.out.println(str);
System.out.println(str.getClass().getName());
}
}
10
10
java.lang.String
Example: Convert int to String using toString() Method
Let's create another example to convert int type to string. Here, we are using toString() method that returns a string of an integer type value.
public class Main {
public static void main(String[] args){
int val = 10;
System.out.println(val);
// int to String
String str = Integer.toString(val);
System.out.println(str);
System.out.println(str.getClass().getName());
}
}
10
10
java.lang.String
Example: Convert using String literals
This is an implicit conversion of int to string type. If we concatenate any type of value to a string then Java converts that expression into a string and returns a string as a result.
public class Main {
public static void main(String[] args){
int val = 10;
System.out.println(val);
// int to String
String str = ""+val;
System.out.println(str);
System.out.println(str.getClass().getName());
}
}
10
10
java.lang.String