How do I convert a String to an int in Java?

How can I convert a String 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 .


String myString = "1234";
int foo = Integer.parseInt(myString);

有关更多信息,请参阅Java文档。


For example, here are two ways:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

There is a slight difference between these methods:

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


    Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.

    int foo;
    String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
    String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
    try {
          foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
    } catch (NumberFormatException e) {
          //Will Throw exception!
          //do something! anything to handle the exception.
    }
    
    try {
          foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
    } catch (NumberFormatException e) {
          //No problem this time, but still it is good practice to care about exceptions.
          //Never trust user input :)
          //Do something! Anything to handle the exception.
    }
    

    It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

    链接地址: http://www.djcxy.com/p/468.html

    上一篇: Javascript的参考价值

    下一篇: 如何在Java中将字符串转换为int?