Bird
0
0

Which code snippet correctly prints "Equal" if either condition is true, and "Not Equal" otherwise?

hard📝 Application Q15 of 15
Kotlin - Operators and Expressions
You want to check if two variables a and b in Kotlin either have the same content or are the exact same object. Which code snippet correctly prints "Equal" if either condition is true, and "Not Equal" otherwise?
A<pre>if (a === b) { println("Equal") } else if (a == b) { println("Not Equal") } else { println("Equal") }</pre>
B<pre>if (a === b && a == b) { println("Equal") } else { println("Not Equal") }</pre>
C<pre>if (a == b) { println("Not Equal") } else if (a === b) { println("Equal") } else { println("Not Equal") }</pre>
D<pre>if (a == b || a === b) { println("Equal") } else { println("Not Equal") }</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Understand the condition needed

    We want to print "Equal" if either a == b (same content) OR a === b (same object) is true.
  2. Step 2: Check each option's logic

    if (a == b || a === b) {
        println("Equal")
    } else {
        println("Not Equal")
    }
    uses logical OR (||) correctly.
    if (a === b && a == b) {
        println("Equal")
    } else {
        println("Not Equal")
    }
    requires both to be true (AND), which is too strict.
    if (a == b) {
        println("Not Equal")
    } else if (a === b) {
        println("Equal")
    } else {
        println("Not Equal")
    }
    incorrectly prints "Not Equal" when a == b is true.
    if (a === b) {
        println("Equal")
    } else if (a == b) {
        println("Not Equal")
    } else {
        println("Equal")
    }
    prints "Not Equal" incorrectly when a == b is true but a === b is false.
  3. Final Answer:

    if (a == b || a === b) -> Option D
  4. Quick Check:

    Use || to combine == and === checks [OK]
Quick Trick: Use || to check either structural or referential equality [OK]
Common Mistakes:
MISTAKES
  • Using && instead of ||
  • Confusing order of conditions
  • Printing wrong messages for conditions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes