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

if(b = i == j) => Valid ??

 
Vaibhav Shridish
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An if statement is supposed to take a boolean value in () how is the following working ?
if( b = i == j)
System.out.println("True");
else
System.out.println("False");
 
Rajeev Nair
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is how the code gets interpreted
if( b = (i == j)) //1
System.out.println("True");
else
System.out.println("False");
on line //1 for what values of i and j ,the condition == will be either true or false. So either true or false will be assigned to b which is a boolean and hence the code works
 
Vaibhav Shridish
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look at this -
This was a question from javacaps where in
if( b = i == j)
System.out.println("True");
else
System.out.println("False");
i and j were assigned values 10 and b has been declared boolean ...
so what are you doing here?
b is being assigned some boolean value
i dont think the expression like (b=something) gives raise to a boolean value for the if() to process ... so y doesnt it result in an error ?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Performing an assignment operation results in the value of the assignment being returned. Normally, we ignore that value because we are only interested in the side-effect, that our variable was set to the given value.
Try this:

You'll see that the result of the assignment, 10, is printed.
When you use a comparison operator, such as ==, a boolean value is returned. Then, you can assign that value to a boolean, such as b, in your example. That assignment has the effect of setting b to the returned value but it also returns the value of the assignment for use in the if test.
I hope that helps,
Corey
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's the old a=b=c=d=e=f=5; trick! Evertybody gets initialized to 5.
So if (b=i==j) works as long as b is a boolean.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic