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");
Vaibhav Shridish
Rajeev Nair
Ranch Hand
Joined: Mar 11, 2002
Posts: 51
posted
0
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
Raj<br />Sun Certified Java Programmer
Vaibhav Shridish
Greenhorn
Joined: Jun 06, 2002
Posts: 28
posted
0
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
Joined: Dec 20, 2001
Posts: 3271
posted
0
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