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:

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(java.lang.String)

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(int)

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

or

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.

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

      System.out.println(x);
      System.out.println(c);
      System.out.println(b);
   }
}
Enter fullscreen mode Exit fullscreen mode

9
5.0
1092

Top comments (0)