Last Updated On By Anmol Lohana
We need integer to string conversion while working with integers or any numbers, sometimes, we need them in string representation. For Example, if you want to print a message that contains integer and string both and you want it to be print in a string form like “I am 22 years old.” This sentence includes integer and string both in it, and we want it in string form.
To do this, we need to concatenate it, and for that purpose, we need to convert an int value into a string value. For converting an integer into a string, there are some methods in Java that we can use.
Table of Contents
The toString() Method is one of the built-in methods of the Java programming language, and it will return the value in string format. On any value, this Method applied like on integer, Boolean, float, and any other primitive type it will always return a string class.
class ToString
{
public static void main(String args[])
{
int a = 1234;
int b = -1234;
String str1 = Integer.toString(a);
String str2 = Integer.toString(b);
System.out.println("First String is " + str1);
System.out.println("Second String is " + str2);
}
}
The format() Method formats the value inside it and return it in string form by a given locale, formatted, and string argument. If the locale is not defined in format() Method it will return the default locale by calling Locale.getDefault() Method.
import java.util.Formatter;
import java.util.Locale;
class FormatMethod {
public static void main(String[] args) {
// create a new formatter
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);
// format a new string
String name = "Zagop IT";
formatter.format(Locale.US,"1. My company's name is %s !"
, name);
// print the formatted string with specified locale
System.out.println("" + formatter + " "
+ formatter.locale());
}
}
The StringBuilder() method or class in Java used to make mutable like modified string objects.
class StringBuilderMethod {
public static void main( String args[] ) {
char[] array = {'5','2','2','1','3'};
StringBuilder setbuilder = new StringBuilder();
for (int i=0; i < array.length; i++)
{
setbuilder.append(array[i]);
}
String string = setbuilder.toString();
System.out.printf("Resultant String is: %s" , string);
}
}
In conclusion, we have discussed how to convert an integer value into a string value in the Java programming language. We discussed three methods that are toString() method, format() method, and StringBuilder() method, with simple code examples to make it more clear.