String to Integer Conversions
source: https://www.geeksforgeeks.org/string-to-integer-in-java-parseint/
Difference between parseInt()
and valueOf()
:
parseInt() parses the string and returns the primitive integer type. However, valueOf() returns an Integer object.
Note:
valueOf()
uses parseInt()
internally to convert to integer.
parseInt()
int decimalExample = Integer.parseInt("20");
int signedPositiveExample = Integer.parseInt("+20");
int signedNegativeExample = Integer.parseInt("-20");
valueOf()
int decimalExample = Integer.valueOf("20");
int signedPositiveExample = Integer.valueOf("+20");
int signedNegativeExample = Integer.valueOf("-20");
Integer to String Conversions
source: https://www.geeksforgeeks.org/different-ways-for-integer-to-string-conversions-in-java/
1.Convert using Integer.toString(int)
class GfG
{
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("String str1 = " + str1);
System.out.println("String str2 = " + str2);
}
}
Convert using String.valueOf(int)
class GfG
{
public static void main(String args[])
{
String str3 = String.valueOf(1234);
System.out.println("String str3 = " + str3);
}
}
3.Convert using Integer(int).toString()
class GfG
{
public static void main(String args[])
{
int d = 1234;
String str4 = new Integer(d).toString();
System.out.println("String str4 = " + str4);
}
}
4.Convert using DecimalFormat
import java.text.DecimalFormat;
class GfG
{
public static void main(String args[])
{
int e = 12345;
DecimalFormat df = new DecimalFormat("#");
String str5 = df.format(e);
System.out.println(str5);
}
}
5.Convert using StringBuffer or StringBuilder
class GfG
{
public static void main(String args[])
{
String str6 = new StringBuffer().append(1234).toString();
System.out.println("String str6 = " + str6);
}
}
StringBuilder
class GfG
{
public static void main(String args[])
{
String str7 = new StringBuilder().append(1234).toString();
System.out.println("String str7 = " + str7);
}
}