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 –

[code lang=”java” highlight=”5″]

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);
}
}

[/code]

 

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 –

  1. Integer.toString() : This methode is availble in wrapper class i.e. in Integer class which returns the string representation of the int argument.
  2. “”+int : This code ultimately compiles to String.
  3. String.valueOf() :  This method internally works as first method i.e. Integer.toString().

Code to convert String to Integer –
[code lang=”java” highlight=”7,11,15″]

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);
}

}

[/code]

One response to “Convert int to String and String to int

  1. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Bitnami