class Bool1 { static boolean b; public static void main(String [] args) { int x=0; if (b ) { //same as: „if (b == true)“ x=1; } else { x=4; } System.out.println("x = " + x + "b ="+b);
} } Appreciate your answers Thomas
Thomas Markl
Ranch Hand
Joined: Mar 08, 2001
Posts: 192
posted
0
I think I've got it now: class Bool { static boolean b; public static void main(String [] args) { int x=0; if (b == true) { //same as if (b ) { x=1; } b = false; else if (b == true) { //same as: else if (b = false) { x=2; } else if (b == true) { // same as: else if (b) { x=3; } else { x=4; //invoked as neiter if nor //if else is fullfilled. } System.out.println("x = " + x); } }
Result: X = 4.
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Originally posted by Thomas Markl: if (b == true) { //same as if (b ) {
yes
b = false; else if (b == true) { //same as: else if (b = false) {
That doesn't compile, as there isn't an "if" the "else" would belong to. If you remove the "else"s, it is correct. Also notice that (b == false) is equivalent to (!b)
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Dave Landers
Ranch Hand
Joined: Jul 24, 2002
Posts: 401
posted
0
Functionally, (b) and (b==true) and (b!=false) are equivalent. And (!b) and (b==false) and (b!=true) are equivalent. But they do not read the same, and using extra unnecessary comparisons to booleans is unnecessary and makes the code much less readable, IMHO. If you'd use a rational name for the variable (like isDone or canRead or willReduceCruft or whatever) rather than "b", then the thing is much more readable using the boolean as a boolean, and not having to compare it to a boolean to get a boolean. Also, putting boolean assignments inside if statements, while legal, can be just plain confusing and will cause maintainence problems and maybe future bugs when someone comes by and replaces the "=" with the "==" that maybe they thought was "supposed to go there". Compare this:
to this:
They both to basically the same thing (execute some code if a boolean is false and switch its value each time). But which would you rather maintain?