• Post Reply Bookmark Topic Watch Topic
  • New Topic

Expression instead of condition in if block  RSS feed

 
Suhas Bilaye
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that in general we write a condition in an if block but...can we write an expression in an if block as in the following code..
Assume the code is inside main method.


This piece of code is from a scjp questionaire posted on the following link (question 2)
scjp
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Not-so-nice response removed. While we encourage people to put some effort into their posts, there are nice ways to put it, and not-so-nice ways. Be sure to use the former.]
 
Anuj Prashar
Ranch Hand
Posts: 99
Android Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes we can write expression in if block as long as it is evaluating to a boolean.



 
Suhas Bilaye
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Anuj....
 
Campbell Ritchie
Marshal
Posts: 56545
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would regard what the question says as a logic error, but then SCJP questions tend to include weird code which one would never use in real life. Similarly, == false and == true count as poor style.

The correct way to write that expression would have been

if (b2 && b1) . . .
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!