Convert int to String and String to int
This is one of the most occurred scenario where we need to convert a Integer to String or a String to Integer.
We can attain that by using methods of wrapper classes. Here we are discussing about Integer -> String or String ->Integer.
String to int
To convert String to Integer we can use parseInt().
Code to convert a number to String –
public class StringToInt { public static void main(String[] args) { String str = "10"; // convert String to int int i = Integer.parseInt(str); System.out.println(i); } }
int to String
To convert Integer to String we can use valueOf() method of String class. although we have few other options to convert an int to String which can be done using following way –
- Integer.toString() : This methode is availble in wrapper class i.e. in Integer class which returns the string representation of the
int
argument. - “”+int : This code ultimately compiles to String.
- String.valueOf() : This method internally works as first method i.e. Integer.toString().
Code to convert String to Integer –
public class IntToString { public static void main(String[] args) { int i = 10; //Method 1 : using Integer.toString() String str1 = Integer.toString(i); System.out.println(str1); //Method 2 : using concatenation with empty string String str2 = "" + i; System.out.println(str2); //Method 3: Using String String.valueOf() String str3 = String.valueOf(i); System.out.println(str3); } }
Wow, amazіng blog layout! How ⅼong have үou been blogging
for? you make blogging look easy. The overall
loօk of your web site iѕ excellent, let alone the content!