Java 如何将String转换为Int

Java 必知必会 第 6 篇

如何将String转换为Int

有两种方式

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.
}
全部评论

相关推荐

白火同学:先说结论,对于一份实习简历来说,整体还是挺不错的,技术深度和广度都到位,找到一份中小厂的实习没啥问题。 再说说能优化的点吧。 1、量化结果,项目中很多工作量化一下结果给面试官的感受会更直观一些,也能体现你对应用该项技术的理解(在众多技术为什么要用它,运行性能或者说开发效率往往是一大考虑指标;而不是说大家做这种功能都用它,所以我用它)。 2、突出亮点,项目中可以从“工作职责”择一些“个人亮点”另写一块,优先去写开发过程中遇到的xx问题,使用xx技术达到xx效果,针对性去写一些疑杂难的功能,能带出你个人思考和解决的过程。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务