java java如何将int转换为boolean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31308896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How java converts int to boolean
提问by Adnan
When i convert:
当我转换时:
int B=1;
boolean A=B;
It gives error: Incompatible types, which is true
它给出了错误:不兼容的类型,这是真的
But when I write this code:
但是当我写这段代码时:
int C=0;
boolean A=C==1;
it gives false while if I change value of C to 1 it gives true. I don't understand how compiler is doing it.
它给出 false 而如果我将 C 的值更改为 1 它给出 true。我不明白编译器是如何做到的。
采纳答案by Uma Kanth
int C=0;
boolean A=C==1;
The compiler first gives C a zero.
编译器首先给 C 一个零。
Variable : C
Value : 0
Now The Assignment statement,
现在赋值语句,
We know that the assignment statement evaluates the right part first and the gives it to the left.
我们知道赋值语句首先计算右边的部分,然后把它交给左边的部分。
The right part ==> C == 1Here, This is an expression which evaluates to trueor false. In this case it is false as c is 0.
右侧部分==> C == 1这里,这是一个计算结果为trueor的表达式false。在这种情况下,它是错误的c is 0.
So the R.H.S is false.
所以 RHS 是错误的。
Now this gets assigned to the L.H.S which is A.
现在这被分配给 LHS,即 A。
A = ( C == 1 ) ==> A = false
As Ais a boolean this is a right statement
作为A一个布尔值,这是一个正确的陈述
回答by Eran
C==1is an expression whose result is boolean(it's the comparison operator). It returns trueif Cequals to 1 and falseotherwise.
C==1是一个表达式,其结果是boolean(它是比较运算符)。true如果C等于 1false则返回,否则返回。
Therefore boolean A=C==1;is a valid assignment of a booleanvalue to a booleanvariable.
因此boolean A=C==1;是boolean对boolean变量的有效赋值。
回答by Jayaram
It checks c==1first and result getting assigned to A.
它c==1首先检查并将结果分配给A.
as Cis not 1 so expression value is resulting to false which is assigned to A
因为C不是 1 所以表达式值导致 false 分配给A

