<< |
Java Quizzes Green = Easy, Blue = Normal, Red = Hard Q25 Q26 Q27 Q28 Q29 Q30 Q31 Q32 Q33 Q34 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 replace the operators with the one of your choice to test it.

### Java quiz 33: Conditional 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

Select the correct answer.

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.

For more questions and the explanations you can join the discussion below!

### Answer explanation

- 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. The statement if((++x == y) || (x++ == y)) returns true, because ++x == y. Therefore, the boolean operand x++ == y is ignored.
- The value of x is incremented by 1 and it becomes 2.
- 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. - The statement x += y; increments the value of x by y, so, x = 4 + 3 = 7.

The correct answer is: c.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!

SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

## Suggested Articles

## Books by Sar Maroof |

Subscribe to Sar Maroof's RSS feeds! Mail this page to a friend! Bookmark this page! |