Object o1 = true ? new Integer(1) : new Double(2.0); System.out.println(o1);
Object o2; if (true) o2 = new Integer(1); else o2 = new Double(2.0); System.out.println(o2);
正确答案:
o1输出的是1.0,o2输出的是1
这个题是看似在考Object类中的方法,但是实际上,这里的三元运算符涉及到一个自动类型提升的问题
(表达式1)?(表达式2):(表达式3)
三元运算的最后结果是这三个表达式中的类型“最高”的一种,在计算的过程个中会有自动类型提升
第五题
1 2 3 4 5 6 7 8 9 10 11
public void method1() { Integer i = new Integer(1); Integer j = new Integer(1); System.out.println(i == j); Integer m = 1; Integer n = 1; System.out.println(m == n);// Integer x = 128; Integer y = 128; System.out.println(x == y);// }
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h;
cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache.high >= 127; } private IntegerCache() {} }