DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

Integer to String and String to Integer in Java

We can use value of :

Alexander Nikiforov on website ( teamtreeHouse)
on Oct 2, 2016
In Java you should use valueOf method for both conversions:

So to convert int to String you write:

int number = 1;
String stringFromNumber = String.valueOf(number);
// shorthand will be
String stringFromNumber = number + "";

Enter fullscreen mode Exit fullscreen mode

To convert int to String is harder, because you have to account for NumberFormatException, see Docs links above:

String numberString = "1";
int intFromString;
try {
  intFromString = Integer.valueOf(numberString);
} catch (NumberFormatException nfe) {
   // do something
   System.out.println(numberString + " is not a number");

Enter fullscreen mode Exit fullscreen mode


we can use parseInt:

This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two.

Following are all the variants of this method −

static int parseInt(String s)
static int parseInt(String s, int radix)

public class Test { 

   public static void main(String args[]) {
      int x =Integer.parseInt("9");
      double c = Double.parseDouble("5");
      int b = Integer.parseInt("444",16);

Enter fullscreen mode Exit fullscreen mode


Top comments (0)