File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

IS if (b ) same as: if (b == true) ???

 
Thomas Markl
Ranch Hand
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Dave Landers
Ranch Hand
Posts: 401
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic