使用强制转换为基本类型的奇怪java行为 [英] Weird java behavior with casts to primitive types

查看:85
本文介绍了使用强制转换为基本类型的奇怪java行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是在某个地方被问到但我找不到它。有人可以澄清为什么这段代码编译并打印出 1

This was probably asked somewhere but I couldn't find it. Could someone clarify why this code compiles and prints out 1?

long i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);


推荐答案

它被解析为:

long i = (byte)( +(char)( -(int)( +(long)(-1) ) ) );

其中所有 + - 运营商是一元 + -

where all the + and - operators are unary + or -.

在这种情况下, 1 被否定两次,因此它打印为 1

In which case, the 1 gets negated twice, so it prints out as a 1.

这篇关于使用强制转换为基本类型的奇怪java行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆