1. don’t initialize string variables with null
instead ofString name = null;
useString name = "";
2. don’t compare string values with ==
instead ofif (name == "John")
useif (name.equals("John"))
3. don’t save numbers or boolean values in String variables
instead ofString price = "100";
useint price = 100;
4. don’t save complex values in String variables
instead ofString addr = "5 main st., burnaby, bc, v1a1a1, CAN";
useAddress addr=new Address(5, "main st.", "burnaby", "v1a1a1", "CAN");
5. don’t concatenate String values, use string formatting instead (or a StringBuilder)
instead ofString info = "1" + " of " + "10" + " from " + "100" + " results";
useString info = String.format("%d of %d from %d results", 1, 10, 1000);
6. don’t compare string values using equals if the casing is different
instead ofboolean areEqual = name.toLowerCase().equals("john smith");
useboolean areEqual = name.equalsIgnoreCase("john smith");
7. do not use multi-line string concatenation
instead ofString textBlock =
"<html>\n" +
" <body>\n" +
" <tag>\n" +
" </tag>\n" +
" </body>\n" +
"</html>";
useString textBlock = """
<html>
<body>
<tag>
</tag>
</body>
</html>""";