java 如何将String转换为Int

标签 IT工具网 java

有两种方式

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

这两种方式有一点点不同: - valueOf返回的是java.lang.Integer的实例 - parseInt返回的是基本数据类型 int

Short.valueOf/parseShort,Long.valueOf/parseLong等也是有类似差别。

另外还需注意的是,在做int类型转换时,可能会抛出NumberFormatException,因此要做好异常捕获

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.
}

stackoverflow链接:http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java

相关文章:

java - 将 Enumeration<T> 视为 Iterator<T>

java - 调用 Post-Method 会导致 "405 Method not allowed"- 错误

如何开始Node.js的学习

杀进程后内存释放顺序导致的问题

java - 基类 C# 和 Java 不同的行为

java - 如何退出包含Java的Callable ExecutiorService MultiThreading的循环(Android)

java.lang.IllegalStateException : [TextView] must not be null

为什么打印“B”会明显的比打印“#”慢

java遍历集合时移除元素,怎样避免ConcurrentModificationException异常抛出