再谈java类型转换

15 篇文章 0 订阅

     晚上一个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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值