Comments (11)
感觉这一题大家都被(Integer) null
误导了,其实(Integer) null
是不会报空指针的,真正的原因来自于隐藏的拆箱操作,因为三元表达式前后类型不一致,前面是Integer
类型,后面是int
类型,所以这里会先将(Integer) null
的值拆成int
类型,把一个null
赋值给一个int
类型的变量就会存在空指针。这里如果把三元表达式后面的parseInt
方法改成valueOf
方法就没有空指针。
from tech-daily-questions.
选A.
解析:
查看Integer.parseInt(s)
方法的源码
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
发现返回值是原生类型,所以在
(s == null) ? (Integer) null : Integer.parseInt(s);
这个三元表达式中会触发自动拆箱导致类型转换异常
from tech-daily-questions.
1.三元表达式 两边类型要一致 会在编译期确定类型 (Integer) null : Integer.parseInt(s)
中,左侧为Integer
包装类型, 右侧为int
类型. 根据三元操作符的转换规则: 左侧的Integer(null)会被转换为int类型,从而保持和右侧一致.此时就会发生自动拆箱操作.
2.包装类型的拆装箱操作调用相应的方法. Integer
装箱方法为Integer.valueOf(int)
. 拆箱方法为integer.intValue()
方法. 根据1中描述,自动拆箱时会执行null.initValue()操作,故运行时会抛出NPE异常
from tech-daily-questions.
选a 这行(Integer) null : Integer.parseInt(s)运行时异常(空指针异常);当parseInt(null)执行时,返回null很正常,但是将null转化成integer对象类型时不对的
from tech-daily-questions.
选a 这行(Integer) null : Integer.parseInt(s)运行时异常(空指针异常);当parseInt(null)执行时,返回null很正常,但是将null转化成integer对象类型时不对的
null可以转化成Integer对象,但不能转成int,这题报空指针的原因就在这里。
from tech-daily-questions.
A
from tech-daily-questions.
选a
from tech-daily-questions.
选A,拆箱会报NPE,但是为什么有拆箱的操作呢?
from tech-daily-questions.
选a,null.intValue(),会报NPE
from tech-daily-questions.
Integer拆箱解箱的NPE问题
from tech-daily-questions.
这题让我理解了java中三元运算符的编译逻辑,谢谢小马哥。
from tech-daily-questions.
Related Issues (4)
- 「小马哥每日一问」2019.08.12 期 HOT 19
- 「小马哥每日一问」2019.08.13 期 HOT 15
- 「小马哥每日一问」2019.08.14 期 HOT 13
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from tech-daily-questions.