Tuesday, June 26, 2018

Technical Tip #25 - Technical Tip of the day....


T25: Knowledge Tip Of The Day.....
Different ways for Integer to String Conversions In Java
1. Convert using Integer.toString(int) :
The Integer class has a static method that returns a String object representing the specified int parameter.
Example :
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);
2. Convert using String.valueOf(int) :
Example :
int c = 1234;
String str3 = String.valueOf(c);
System.out.println("String str3 = " + str3);
OR
String str3 = String.valueOf(1234);
System.out.println("String str3 = " + str3);
3. Convert using Integer(int).toString()
This methods uses instance of Integer class to invoke it’s toString() method.
Example :
int d = 1234;
Integer obj = new Integer(d);
String str4 = obj.toString();
System.out.println("String str4 = " + str4);
OR
int d = 1234;
String str4 = new Integer(d).toString();
System.out.println("String str4 = " + str4);
4. Convert using DecimalFormat
The class java.text.DecimalFormat is a class that formats a number to a String.
int e = 12345;
DecimalFormat df = new DecimalFormat("#");
String str5 = df.format(e);
System.out.println(str5); // String str5 = 12345
OR
int e = 12345;
DecimalFormat df = new DecimalFormat("#,###");
String Str5 = df.format(e);
System.out.println(Str5); // String str5 = 12,345

No comments:

Post a Comment