Consider the following code segment. What is printed as a result of executing the code segment?
int a = 12;
int b = 12;
System.out.println(a == b);
System.out.println(a != b);
true followed by truetrue followed by falsefalse followed by truefalse followed by falsea and b hold the same number, == produces true and != produces false.
Explanation
Primitive values are compared by value. Two int variables are equal when they hold the same number. The equality operator asks whether the values match, and the inequality operator asks the opposite question, so the two results are always opposites.
- A is not correct: the second line uses
!=, which asks whether the values differ; equal values make that comparison producefalse. - C is not correct:
aandbhold the same number, so==producestruerather thanfalseon the first line. - D is not correct: both comparisons cannot be
falseat once, because==and!=ask opposite questions about the same two values.