Java quiz 33: Conditional vs bitwise operator

 Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge
 > < Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard Select    31   32   33   34   35   36   37   38   39   40   41   42   43   44   By title

This Java quiz demonstrates the difference between conditional operator || with the bitwise operator |. To understand the difference you can play with the code and change the operators to test it.

Java quiz 33: Conditional operator vs bitwise operator

Level: Normal

What is the output of the following code?

public class MyOperator
{
public static void main(String[] args)
{
int x = 1;
int y = 2;
if((++x == y) || (x++ == y))
{
if((x++ == y++) | (++x == y))
{
x += y;
}
}
System.out.println(x);
}
}
Author: Sar Maroof

a. This program writes “8” to the standard output.
b. This program writes “6” to the standard output.
c. This program writes “7” to the standard output.
d. This program writes “5” to the standard output.
e. This program writes “4” to the standard output.
f. Illegal at compile time.
g. Illegal at run time.

If the first boolean operand is true by conditional operator || the second boolean operand is ignored.
By the bitwise operator | all the boolean operands are evaluated regardless of their results.

1. The statement if((++x == y) || (x++ == y)) returns true, because ++x == y. Therefore, the boolean operand x++ == y is ignored.
2. The value of x is incremented by 1 and it becomes 2.
3. The statement if((x++ == y++) | (++x == y)) returns true, because x++ = y++.
Therefore, the value of x is incremented by 1. x = 3. The value of y is also incremented by 1. y = 3. The boolean operand ++x == y is also evaluated. Therefore the value of x is incremented by 1. So, x = 3 + 1 = 4.
4. The statement x += y; increments the value of x by y, so, x = 4 + 3 = 7. Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.