Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

if(boolean)

 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What is program logic behind the above pgm.In the getBoolean(), we are checking whether the number is generated randomly is zero. If so, we return false elase we return true. Correct me, if i am wrong.

Whether the if statment returns the boolean expr. that is if(boolean) is possible in java. I think I am messing up something?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

if((int) (Math.random() * 2) ==0);

This particular conditional statement does nothing. The clue as to why is in bold. (It shouldn't even compile).
[ August 11, 2005: Message edited by: Paul Sturrock ]
 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, It is typographical error. There is no semicolon at the end of the if statement.

Correct one:
if((int) (Math.random() * 2) ==0)
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Niyas Ahmed Sheikh:


What is program logic behind the above pgm.In the getBoolean(), we are checking whether the number is generated randomly is zero. If so, we return false elase we return true. Correct me, if i am wrong.

Whether the if statment returns the boolean expr. that is if(boolean) is possible in java. I think I am messing up something?


(int) (Math.random() * 2) will return either 0 or 1, therefore having getBoolean() return true or false depending on the returned value is simple a way of generating a random boolean value.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As an aside,

if (x) return true; else return false;

can be nicely shortened to

return x;
 
Marilyn de Queiroz
Sheriff
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the getBoolean(), we are checking whether the number is generated randomly is zero. If so, we return false; else we return true. Correct me, if i am wrong.

true.

Whether the if statment returns the boolean expr. that is if(boolean) is possible in java.

"if (boolean)" is not only possible in Java, it is the only way to write an if statement. "if (0)" (or any other int) will not compile.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic