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 == 1
Here, This is an expression which evaluates to true
or false
. In this case it is false as c is 0.
右侧部分==> C == 1
这里,这是一个计算结果为true
or的表达式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 A
is a boolean this is a right statement
作为A
一个布尔值,这是一个正确的陈述
回答by Eran
C==1
is an expression whose result is boolean
(it's the comparison operator). It returns true
if C
equals to 1 and false
otherwise.
C==1
是一个表达式,其结果是boolean
(它是比较运算符)。true
如果C
等于 1false
则返回,否则返回。
Therefore boolean A=C==1;
is a valid assignment of a boolean
value to a boolean
variable.
因此boolean A=C==1;
是boolean
对boolean
变量的有效赋值。
回答by Jayaram
It checks c==1
first and result getting assigned to A
.
它c==1
首先检查并将结果分配给A
.
as C
is not 1 so expression value is resulting to false which is assigned to A
因为C
不是 1 所以表达式值导致 false 分配给A