1 package day1_28;
2
3 import org.junit.Test;
4
5 /**
6 * 三元运算符
7 * 条件表达式 ? 表达式1 :表达式2
8 * 重点注意:表达式1和表达式2 要求是一致的
9 */
10
11 public class InterviewTest {
12 @Test
13 public void test1() {
14 //一般使用
15 int a = 10;
16 int b = 20;
17 int max = a > b ? a : b;
18 System.out.println("最大值:" + max);
19 }
20
21 @Test
22 public void test2() {
23 //特殊情况
24 int i = 33;
25 float f = 22;
26 //编译报错
27 // 首先表达式1和表达式2不一致,编译器会将两者通过int-->float类型自动提升,
28 //结果肯定是float类型,所以int类型变量接收运算结果报错
29 // int max2 = i>f ? i : f;
30
31 float max3 = i>f ? i : f;
32 System.out.println(max3); //33.0
33 }
34
35 @Test
36 public void test3() {
37 //多态和包装类的情况
38
39 //由于包装类的自动包装和拆装,所以下面是可以比较的
40 boolean result = (new Integer(66)>new Float(22.0f));
41 System.out.println(result);
42 Object object = result ? new Integer(66) :new Float(22.0f);
43 //打印出什么结果呢?
44 System.out.println(object);
45 }
46
47
48 @Test
49 public void test4() {
50 //包装类的缓存
51
52 Integer i = new Integer(11);
53 Integer j = new Integer(11);
54 //使用new创建对象,==比较的是两个对象的引用地址
55 System.out.println(i==j); //false
56
57
58 Integer m = 22;
59 Integer n = 22;
60 //上面用到了自动装箱,看源码就知道,Integer类内部定义了IntegerCache内部类
61 // 这个内部类中有一个成员变量是Integer[],缓存了范围的整数,如果
62 // 我们使用自动装箱,给Integer赋值的范围在[-128,127]内时,可以直接使用数组
63 //中的的元素,不用再去new了。目的:提高效率
64 System.out.println(m == n); //true
65
66 Integer x = 128;
67 Integer y = 128;
68 //和上面一样的原理,超过了[-128,127]的范围,
69 // Integer类就会使用new Integer(int value)构造器创建Integer对象,
70 //这个时候 == 比较的就是两个对象的引用地址了
71 System.out.println(x == y);//false
72 }
73
74 }