晚上一个java群里发来了下面代码,问原因,一时我也没有看出来为什么第2个打印结果会是“88”。想看一下三目运算的源码没找到。于是想到C语言以前写过结构体实现三目运算比较,因此猜到此可能是类型转换导致的。网上一找java编程规范果然是如此。
@org.junit.Test
public void printIfElse()
{
char x='X';
// int i=0; // X 88
// float i = 12.33232f; //X 88.0
double i = 129;// X 88.0
System.out.println(true?x:0);
System.out.println(false?i:x);
}
If one of the operands is of type byte or Byte and the other is of type short or Short, then the type of the conditional expression is short.
If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.
If one of the operands is of type Byte and the other operand is a constant expression of type int whose value is representable in type byte, then the type of the conditional expression is byte.
If one of the operands is of type Short and the other operand is a constant expression of type int whose value is representable in type short, then the type of the conditional expression is short.
If one of the operands is of type; Character and the other operand is a constant expression of type int whose value is representable in type char, then the type of the conditional expression is char.