2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > string转换为bigdecimal_java如何将String转换为Int

string转换为bigdecimal_java如何将String转换为Int

时间:2020-08-08 12:21:19

相关推荐

string转换为bigdecimal_java如何将String转换为Int

Java 必知必会 第 1篇(精挑 Stack Overflow在java中排名前100的问题懂得这些问题的答案帮你解决80%开发问题)问题:

java如何将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.

}

这将会是一个系列,我接下来会更新mysql,mongodb,java,linux等,精挑 Stack Overflow在中排名前的问题,一般知道这些问题,可以帮助我们快速解决开发中遇到80%的问题。

推荐阅读:

用一年的时间带你读懂《深入理解计算机系统》

500+ 免费的中文编程电子书

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。