Int to String conversion
There are two ways to convert an integer value to a String.
1) Using String.valueOf(int i): This method takes integer value as an argument and returns a string representing the int augment.
Method declaration:
public static String valueOf(int i)
parameters:
i – integer that needs to be converted to a string
returns:
A string representing the integer argument
1) Using String.valueOf(int i): This method takes integer value as an argument and returns a string representing the int augment.
Method declaration:
public static String valueOf(int i)
parameters:
i – integer that needs to be converted to a string
returns:
A string representing the integer argument
int var = 123; String strg = String.valueOf(var);
2) Using Integer.toString(int i): This method works same as String.valueOf(int i) method. It belongs to the Integer class and converts the specified integer value to String. for example if passed value is 123 then the returned string value would be “123”.
Method declaration:
public static String toString(int i)
parameters:
i – integer that requires conversion
returns:
String representing the integer i.
Method declaration:
public static String toString(int i)
parameters:
i – integer that requires conversion
returns:
String representing the integer i.
int var = 200; String strg = Integer.toString(var);
Example:
This program demonstrates the use of both the above mentioned methods(valueOf and toString). Here we have two integer variables and we are converting one of them using String.valueOf(int i) method and other one using Integer.toString(int i) method.
public class ConvertInt { public static void main(String[] args) { // using valueOf() method of String class. int var = 333; String strg = String.valueOf(var); System.out.println("String is: "+strg); // Method 2: using toString() method of Integer class int var1 = 302; String strg1 = Integer.toString(var1); System.out.println("String1 is: "+strg1); } }
Output:
String is: 333 String1 is: 302
Comments
Post a Comment