0
0
JUnittesting~20 mins

assertSame and assertNotSame in JUnit - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
JUnit assertSame Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of assertSame with identical objects
What will be the result of this JUnit test method execution?
JUnit
String a = "test";
String b = a;
assertSame(a, b);
ATest throws NullPointerException
BTest fails with AssertionError
CTest passes without error
DCompilation error due to assertSame usage
Attempts:
2 left
💡 Hint
assertSame checks if both references point to the exact same object.
Predict Output
intermediate
2:00remaining
Result of assertNotSame with different objects
What happens when this JUnit assertion runs?
JUnit
String a = new String("hello");
String b = new String("hello");
assertNotSame(a, b);
ATest passes without error
BTest fails with AssertionError
CCompilation error due to assertNotSame usage
DTest throws IllegalArgumentException
Attempts:
2 left
💡 Hint
assertNotSame checks that two references do not point to the same object.
assertion
advanced
2:00remaining
Which assertion fails here?
Given these variables, which assertion will fail when executed?
JUnit
Integer x = 128;
Integer y = 128;
assertSame(x, y);
assertNotSame(x, y);
ABoth assertions pass
BassertNotSame(x, y) fails
CBoth assertions fail
DassertSame(x, y) fails
Attempts:
2 left
💡 Hint
Integer caching affects small values but not 128.
🧠 Conceptual
advanced
2:00remaining
Purpose of assertSame vs assertEquals
Which statement correctly explains the difference between assertSame and assertEquals in JUnit?
AassertSame checks if two references point to the same object; assertEquals checks if two objects are logically equal.
BassertSame checks object content equality; assertEquals checks reference equality.
CassertSame throws exception on nulls; assertEquals ignores nulls.
DassertSame compares primitive values; assertEquals compares object references.
Attempts:
2 left
💡 Hint
Think about identity vs equality.
🔧 Debug
expert
3:00remaining
Why does this assertSame fail unexpectedly?
Consider this test code snippet: String a = "abc"; String s1 = a + "def"; String s2 = "abcdef"; assertSame(s1, s2); Why does assertSame fail here?
ABecause assertSame cannot be used with String objects
BBecause string concatenation at runtime creates new objects, so references differ
CBecause s1 and s2 are different String objects despite having same content
DBecause s2 is null causing NullPointerException
Attempts:
2 left
💡 Hint
Consider when Java creates String objects and how concatenation works.