An integer x can be converted to a boolean, following the C language convention that any nonzero value is true, by the expression x!=0. An object reference obj can be converted to a boolean, following the C language convention that any reference other than null is true, by the expression obj!=null.
What does this mean? I thought a Boolean could not be converted or casted to anything. JLS-4.2.5
Like this for instance: int x = 1; int y = 0; boolean b1 = (x!=0); // b1 is true boolean b2 = (y!=0); // b2 is false Object o1 = new Object(); Object o2 = null; boolean b3 = (o1!=null); // b3 is true boolean b4 = (o2!=null); // b4 is false
correct a boolean can not be cast to anything -- but notice they're not casting it -- basically its just an expression just like any other, the result of which is of the type boolean, try typing it into a lil class and run it. It's not really magic. Take the first expression: int x = 1; boolean y; y = x != 0; //returns true it simply assigns the result of the expression x!=0 to the value of y. int x = 0; boolean y; y = x != 0; //returns false
Hmm. Your example has two integers: x and y. x is used in the boolean expression x!=0 . y is used in the boolean expression y!=0 . Both expressions return a boolean and are assigned to boolean values. At what point are the integers x and y converted to booleans?
Joined: Aug 26, 2001
The integers are not converted to boolean values, but the comparison of the integer value with the value 0 yields a boolean which is assigned to a boolean primitive. In this respect I must admit that the JLS terminology is erroneous since an integer cannot be converted to a boolean. But you get the idea, don't you? [ July 10, 2002: Message edited by: Valentin Crettaz ]
Joined: Jun 26, 2002
I took the words from the JLS passage literally: "...An integer x can be converted to a boolean..." My confusion was really about those words, not the code itself. Thanks for your help.
You're right - a integer can not be transformed into a boolean in Java. The reason this is shown is because this was a trick often used in C++:
You see, in C and C++, an int could be used wherever boolean was expected. The value was interpreted as 0 = false and anything else = true. All the JLS is talking about is how to build an expression that allows you to do something similar in Java in spite of the fact that you can't actually an integer where a boolean in expected. Rather, you can use a boolean expression involving an integer where a boolean is expected. I hope that helps, Corey