Java 必知必会 第 1 篇
(精挑 Stack Overflow在java中排名前100的问题
懂得这些问题的答案帮你解决80%开发问题 )
问题:
答案:
有两种方式
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
这两种方式有一点点不同:
valueOf
返回的是 java.lang.Integer
的实例parseInt
返回的是基本数据类型 intShort.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.
}
这将会是一个系列,我接下来会更新mysql,mongodb,java,linux等,精挑 Stack Overflow在中排名前的问题,一般知道这些问题,可以帮助我们快速解决开发中遇到80%的问题。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有