How java converts int to boolean

ぐ巨炮叔叔 提交于 2020-02-02 04:10:31

问题


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.


回答1:


int C=0;
boolean A=C==1;

The compiler first gives C a zero.

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.

So the R.H.S is false.

Now this gets assigned to the L.H.S which is A.

A = ( C == 1 ) ==> A = false

As A is a boolean this is a right statement




回答2:


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.

Therefore boolean A=C==1; is a valid assignment of a boolean value to a boolean variable.




回答3:


It checks c==1 first and result getting assigned to A.

as C is not 1 so expression value is resulting to false which is assigned to A



来源:https://stackoverflow.com/questions/31308896/how-java-converts-int-to-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!