Strong Type Conversion

Java has implicit type conversions in built for most of the convertable types, such as conversion from int to long, and byte to short, int and long, float to double and even char to int.

But never from a short to byte, doing so would cause a compilation error.

Conversion at the computational level is rather different. Though we would implicitly understand a conversion of short 127 to byte 127, the compiler has a warning built in. This is because of potential loss of information when converting from a high bit type to a lower one.

short shorty = 127;
byte bitty = shorty;


Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from short to byte

	at typeConversion.Demo01.main(Demo01.java:7)

Of course, we can force Java to convert things with "strong conversion", thereby absolving the compiler of all responsibility.

		short shorty = 127;
		byte bitty = (byte) shorty;
		System.out.println(bitty);

And as expected, it can run perfectly fine.

But what happens if you try to convert something larger?

		short shorty = 128;
		byte bitty = (byte) shorty;
		System.out.println(bitty);

Unexpectedly, it can still compile even though the Byte type in Java has a valid range of -128 ~ 127. The printed result is not 128 as expected, but rather -128.

-128

So what happened? When you convert something what happens at the computational level is that bits of information (0s and 1s) are moved over into that type, like below.

In technical terms, the leftmost bit is the signed. All Java number types are signed, meaning that one of the bit is used to check if the value is positive or negative. When converting from Short, the value 128 is stored as a 1 in the same place as the sign for Byte, causing that to shift over and resulting in:

Typesign163848192409620481024512256128/sign6432168421Result
Short0000000010000000128
Byte01111111127     
Convert10000000

-128

This is also behind what happens in an overflow bug, where going over the value's valid representations will cause it to overflow into the negatives.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值