简体   繁体   English

JAVA比较何时会得出布尔值? 在运行时还是在编译时?

[英]JAVA When do comparisons evaluate to boolean values? At run-time or at compile-time?

In Java, When do the comparisons evaluate to boolean values? 在Java中,比较何时会评估为布尔值? Is it at run-time or it is at compile-time? 是在运行时还是在编译时? For instance, Imagine this: 例如,想象一下:

int x = 6; 
if (x > 7) { doSth(); }

After the compilation will it be represented as "x > 7" in the bytecode or it will be represented as a boolean value "false"? 编译后,它将在字节码中表示为“ x> 7”还是将其表示为布尔值“ false”?

It depends on the compiler. 这取决于编译器。

Some compilers will try to be clever, and where possible, evaluate expressions at compile time. 一些编译器会尝试变得更聪明,并在可能的情况下在编译时评估表达式。 Such compilers will recognise that, at the time of the if statement, x can only be 6 , and thus x < 7 will always be false. 这样的编译器将认识到,在执行if语句时, x只能为6 ,因此x < 7将始终为false。 They may even remove the block that is guarded by this if statement. 他们甚至可以删除此if语句保护的块。

However, there is no obligation for compilers to do this. 但是,编译器没有义务这样做。 A simplistic compiler may not perform any such operations, and the entire code will make its way into the bytecode despite there being no chance of it ever being executed. 简单的编译器可能不会执行任何此类操作,并且即使没有执行的可能,整个代码也会进入字节码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM