public class CheckString
{
public static void main(String[] args)
{
String s1 = "LOC"; //store at String Constant Pool(SCP)
String s2 = new String("LOC"); //store at heap memory
String s3 = "LOC"; //store at SCP
String s4 = new String("LOC"); //store at heap memory
if(s1 == s3) //output: s1 ==s3
System.out.println("s1 == s3");
else
System.out.println("s1 != s3");
if(s1 == s2) //output: s1 != s2
System.out.println("s1 == s2");
else
System.out.println("s1 != s2");
if(s2 == s4) //output: s2 != s4
System.out.println("s2 == s4");
else
System.out.println("s2 != s4");
if(s1.equals(s2)) //output: content of s1 same as s2
System.out.println("content of s1 same as s2");
else
System.out.println("s1 and s2 have different content");
if(s4.equals(s2)) //output: content of s4 same as s2
System.out.println("content of s4 same as s2");
else
System.out.println("s4 and s2 have different content");
//String is immutable
s1 = "COSI350"; //s1 points to another location of SCP
if(s1 == s3) //output: s1 points to another location
System.out.println("s1 == s3");
else
System.out.println("s1 points to another location");
}
}
public class CheckStringBuilder
{
public static void main(String[] args)
{
String s1 = new String("LOC"); //store at heap memory
StringBuilder s2 = new StringBuilder("LOC"); //store at heap memory
String s3 = new String("LOC"); //store at heap memory
StringBuilder s4 = new StringBuilder("LOC"); //store at heap memory
System.out.printf("s1: %d\n", s1.hashCode());
System.out.printf("s2: %d\n", s2.hashCode());
System.out.printf("s3: %d\n", s3.hashCode());
System.out.printf("s4: %d\n", s4.hashCode());
// String is immutable, StringBuilder is mutable
s1 = s1 + "-COSI350";
s2.append("-COSI350");
System.out.println("After update s1 & s2,");
System.out.printf("s1: %d\n", s1.hashCode());
System.out.printf("s2: %d\n", s2.hashCode());
System.out.printf("s3: %d\n", s3.hashCode());
System.out.printf("s4: %d\n", s4.hashCode());
System.out.printf("s1= %s\n", s1);
System.out.printf("s2= %s\n", s2);
}
}

StringBuffer performs faster than StringBuilder
StringBuilder(synchronization) is more safe than StringBuffer