aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes if(b = i == j) => Valid ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "if(b = i == j) => Valid ??" Watch "if(b = i == j) => Valid ??" New topic
Author

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

Vaibhav Shridish
Greenhorn

Joined: Jun 06, 2002
Posts: 28
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
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
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
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


SCJP Tipline, etc.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
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.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: if(b = i == j) => Valid ??
 
Similar Threads
For loop
What will be the output of following program? explain why?
Inner Loop
Yet another style question
can we store an integer in a byte array