Converting String to int in Java?

Posted by  Manoj Bhatt
Java  String 
 1518  View(s)
Rate this:
How can a String be converted to an int in Java?

My String contains only numbers and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.
  1. Re: Converting String to int in Java?

    Integer x = Integer.valueOf(str);
    // or
    int y = Integer.parseInt(str);
    There is a slight difference between these methods:

    valueOf returns new instance of java.lang.Integer
    parseInt returns primitive int.
    The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.