I would like to check if strings are accidentally compared with the == operator. My approach is to try to create new strings in the testcases instead of using string literals, so that comparisons like actualString == testParameter evaluate to false in the test subject, even though the contents of the strings are equal. This hopefully creates unexpected behaviour and leads to test failure. To do this I need to create a new string object in Java. How can I do so reliably?
String a = "I am the same.";
String b = "I am the same."; // Does not create a new String.
String c = new String("I am the same.");
String d = new StringBuilder().append("I am the same.").toString();
Are the last two lines guaranteed to create new string objects? If you know of another approach, please let me know.