java如何将int转换为boolean [英] How java converts int to boolean
问题描述
当我转换时:
int B=1;
boolean A=B;
它给出了错误:类型不兼容
但是当我编写这段代码时:
But when I write this code:
int C=0;
boolean A=C==1;
给出错误 而如果我将C的值更改为1,则表示为true. 我不明白编译器的工作方式.
it gives false while if I change value of C to 1 it gives true. I don't understand how compiler is doing it.
推荐答案
int C=0;
boolean A=C==1;
编译器首先给C赋零.
Variable : C
Value : 0
现在,Assignment语句,
Now The Assignment statement,
我们知道,赋值语句首先评估右侧部分,然后将其赋予左侧.
We know that the assignment statement evaluates the right part first and the gives it to the left.
右侧部分==> C == 1
在这里,这是一个表达式,其结果为true
或false
.在这种情况下,它为c is 0.
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.
所以R.H.S是假的.
So the R.H.S is false.
现在将其分配给L.H.S,即A.
Now this gets assigned to the L.H.S which is A.
A = ( C == 1 ) ==> A = false
由于A
是布尔值,所以这是正确的声明
As A
is a boolean this is a right statement
这篇关于java如何将int转换为boolean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!