DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay