๐งช Unit Test 002: String Comparison โ
๐ Preface โ
In Java, comparing strings with == instead of .equals() is a classic source of bugs. While they can sometimes give the same result, the two approaches have entirely different meanings. This test case exposes that difference and shows how Java's internal handling of strings (like interning) affects comparison.
๐ฌ Test Case โ
java
public class T_002_StringComparison {
@Test
public void test() {
String str1 = "Hello"; // Interned String
String str2 = "Hello"; // Also interned String
String str3 = new String("Hello"); // Not an interned String
String str4 = str3.intern(); // Once again an interned String
Assertions.assertSame(str1, str2);
Assertions.assertNotSame(str1, str3);
Assertions.assertSame(str1, str4);
Assertions.assertEquals(str1, str2);
Assertions.assertEquals(str1, str3);
Assertions.assertEquals(str1, str4);
}
}๐ Why This Matters โ
Using == compares references, not content. While string literals are interned and may point to the same memory, dynamically created strings are not. Always use .equals() when comparing string values. Misusing == can lead to logic bugs, especially when strings come from user input, APIs, or file I/O.