10行代码2道题,全答对的你月薪多少了?

题目1:

public static void demo01() {    Integer f1 = 100, f2 = 100, f3 = 200, f4 = 200;    System.out.println(f1 == f2);    System.out.println(f3 == f4);}

题目2:

private static Integer i;public static void demo02() {    if (i == 0) {        System.out.println("A");    } else {        System.out.println("B");    }}

|

|

|

|

|

|

|

|

|

|

题目1答案:

true

false

题目2答案:

NullPointerException

解析:

题目1:

以下是Integer类中“自动装箱”的源码:

public static Integer valueOf(int i) {    if (i >= IntegerCache.low && i <= IntegerCache.high)        return IntegerCache.cache[i + (-IntegerCache.low)];    return new Integer(i);}

其中IntegerCache.low的是值是-128,IntegerCache.high的值是127。也就是说,Integer在自动装箱时,如果判断整数值的范围在[-128,127]之间,则直接使用整型常量池中的值;如果不在此范围,则会new 一个新的Integer()。因此,本题f1和f2都在[-128,127]范围内,使用的是常量池中同一个值。而f3和f4不在[-128,127]范围内,二者的值都是new出来的,因此f3和f4不是同一个对象。

题目2:

Integer i 的默认值是null。当执行 i==0 时,等号右侧是数字,因此为了进行比较操作,Integer会进行自动拆箱(也就是将Integer转为int类型)。很明显,如果对null进行拆箱(将null转为数字),就会报NullPointerException。

都答对了么?

本文分享自微信公众号 - 大数据和人工智能技术(Big_Data-AI)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java中Integer的特殊之处

首先来看一个例子:<!lang:javaIntegera110;Integera210;System.out.println(a1a2);Integerb1newInteger(100);Integer

Quartz结合SPRING多任务定时调用

public class QuartzJob {      public void work()      {              System.out.println(Spring Quartz的任务调度1被调用!");              //定时调用的业务逻辑      }

Photoshop键盘快捷键&nbsp;&nbsp;&nbsp;操作更方便

使用快捷键快速操作.F1帮助F2剪切F3拷贝F4粘贴F5隐藏/显示画笔面板F6隐藏/显示颜色面板F7隐藏/显示图层面板F8隐藏/显示信息面板F9隐藏/显示动作面板F12恢复ShiftF5填充ShiftF6羽化ShiftF7选择→反选Ctrlh隐藏选定区域Ctrld取消选定区域C

Linux系统初始化脚本

查看centos的版本号CentOS_versioncutd""f4/etc/centosrelease|cutd"."f1改变PS3格式PS3"Pleaseentertheoptionyouneedtooptimize:"网卡名称netw

SpringQuartz定时任务调度器

JAVA代码测试类public class TestQuartz {public void test(){System.out.println("Quartz的任务调度");}}Quartz配