public class Test {
public static void main (String [] args) {
int x = 4;
System.out.println("value is " + ((x > 4 ) ? 99.0 : 9));
}
}
输出 value is 9.0public class Test {
public static void main (String [] args) {
int x = 4;
System.out.println("value is " + ((x > 4 ) ? 99 : 9));
}
}
输出 value is 9为什么会这样? 求解

解决方案 »

  1.   

    第一个是因为你的9是int型的 而99.0是float型的 所以9会自动转换成float型输出
    而第二个因为两个都是int型的 所以不用转换输出
      

  2.   

    补充1楼:99.0不是float,而是double。其他分析均正确。谢谢。
      

  3.   

    关于这个还有点复杂,The Java Programming Language上是这样说的:
    The conditional operator expression has a type that is determined by the types of the second and third expressions (usersValue and defaultValue in the above example). If the types of these expressions are the same then that is the type of the overall expression. Otherwise, the rules get somewhat complicated:If one expression is a primitive type and the other can be unboxed to become a compatible primitive type, then the unboxing occurs and the expressions are reconsidered.If both expressions are numeric primitive types then the resulting type is also a numeric primitive type, obtained by numeric promotion if needed. For example, indouble scale = (halveIt ? 0.5 : 1);the two expressions are of type double (0.5) and type int (1). An int is assignable to a double, so the 1 is promoted to 1.0 and the type of the conditional operator is double.If one expression is an int constant, and the other is byte, short, or char, and the int value can fit in the smaller type, then the resulting type is that smaller type.If one of the expressions is a primitive type and the other is a reference type that can't be unboxed to get a compatible value, or both expressions are primitive but incompatible, then the primitive type is boxed so that we have two reference types.Given two reference types that are different, the type of the expression is the first common parent type. For example, if both expressions were unrelated class types that implemented Cloneable then Cloneable would be the type of the expression; if one expression was int while the other was String, then Object would be the resulting type.
    当然Java语言规范上的好像还要难懂一些,有兴趣可以自己去看看。
      

  4.   

    答:上边英文的内容,最重要的就是一条:
    若一个是int型常量表达式,另一个是byte,short,char,而常量值在byte,short,char的表示范围内,则按byte,short,char类型运算。这是对两者类型往大的转的补充
    如:表达式:false?'A':66
    这个表达式是什么类型?用System.out.println(...)输出值是什么?
    1)是char类型(不是int) 
    2)输出是'B',而不会是值66
      

  5.   

    这种隐式转换在 Java Language Specification 中称为双目数值提升(binary numeric promotion)详见:
    http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#341287 
    http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983或者下面这个帖子的 109 楼:http://topic.csdn.net/u/20080407/09/dabcc399-4460-47ef-966f-26bcb800bd39.html