In this blog I will be talking about comparing strings and understanding the String class in detail. As a start string classes are “immutable and final” by nature. These two attributes of the String class go hand-in-hand. If strings have to be immutable, they need be declared final and vice-versa. A final class cannot be overridden so once a method is declared final, they cannot be modified.
The most important thing to understand here is that the JVM memory model for Strings are a bit different from other objects. Strings have a separate memory area called the string constant pool in addition to the heap memory. This helps with immutability of strings.
The following illustration shows why a string reference variable created using ” ” (apostrophe character) is not the same as String created using the ‘new’ keyword. For example –
Let’s say we have two strings –
String s1 = "Hello World !!";
String s2 = new String ("Hello World !!");
We want to compare the s1 and s2 using the == symbol and the equals keyword.
In order to do this I first write a simple StringComparisonDemo class with two methods as shown below and then create unit test to assert expected vs actual results.
public String compareS1EqualsKeywordS2(String s1, String s2) {
String result = null;
if (s1.equals(s2)) {
result = "equal";
} else {
result = "not equal";
}
return result;
}
public String compareS1EqualToSymbolsS2(String s1, String s2) {
String result = null;
if (s1 == s2) {
result = "equal";
} else {
result = "not equal";
}
return result;
}
Unit test #1 – “compareS1EqualsS2″ will compare s1 and s2 values for equality character by character Unit test #2 – “compareS1EqualToSymbolS2” will compare reference variables
@Test
void compareS1EqualsS2() {
String expected = "equal";
StringComparisonDemo demoInstance = new StringComparisonDemo();
String actual = demoInstance.compareS1EqualsS2(s1, s2);
assertEquals(expected, actual);
}
@Test
void compareS1EqualToSymbolS2() {
String expected = "not equal";
StringComparisonDemo demoInstance = new StringComparisonDemo();
String actual = demoInstance.compareS1EqualToSymbolsS2(s1, s2);
assertEquals(expected, actual);
}
I have attached screenshot of the StringComparisonDemo and the Junit test results below.
StringComparisonDemo.java

Junit Result

Leave a Reply