File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Operators and Assignments?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Operators and Assignments??" Watch "Operators and Assignments??" New topic
Author

Operators and Assignments??

leow
Greenhorn

Joined: Jan 18, 2002
Posts: 3
What gets printed on the standard output when the class below is compiled and executed. Select the one correct answer.
1. public class ShortCkt {
2.public static void main(String args[]) {
3.int i = 0;
4.boolean t = true;
5.boolean f = false, b;
6.b = (t && ((i++) == 0));
7.b = (f && ((i+=2) > 0));
8.System.out.println(i);
9.}
10. }

A)0
B)1
C)2
D)3
why the answer is b? and why (line 7) second assignment to variable b, the expression (i+=2) does not get evaluated? please explain, thanks..
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
This is an example of the short-circuit operation of the && operator.

b = (f && ((i+=2) > 0));

At this point, variable f has the value false. The operator is a logical AND (&&). The result of false AND true or false AND false is : false.
So the statement does not need to be evaluated completely to know that b will be assigned the value false. The rest of the statement after && is ingored, so the side-effect of the i increment is never performed.
Rob


Rob
SCJP 1.4
leow
Greenhorn

Joined: Jan 18, 2002
Posts: 3
thanks Rob, what if the && change to & or |, the statement will be evaluated completely?
b = (f & ((i+=2) > 0)); or
b = (f | ((i+=2) > 0));
thanks..
Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
in that case both will be evaluated
/SAmith
Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
Originally posted by leow:
thanks Rob, what if the && change to & or |, the statement will be evaluated completely?
b = (f & ((i+=2) > 0)); or
b = (f | ((i+=2) > 0));
thanks..

sorry i'll explain in more detail
the AND (&) opertator results in TRUe id both the operand are True and the OR operator (|) results in TRUE if either one of the operands are TRUE.
unlike the Logical AND , OR the Boolean AND, OR check BOTH the operands to get the result.
so in your example both the operands will be evaluated.
/SAmith
 
wood burning stoves
 
subject: Operators and Assignments??