// sample program to demonstrate equals vs == and interning of strings public class StringFun { public static void main(String[] args) { // all of these strings will be .equals to each other // the question is when are they == to each other String s1 = "hello"; String s2 = "hello"; String s3 = "he" + "llo"; // these first 3 strings are all computed at compile // time, so the compiler is able to intern them System.out.println(s1 == s2); System.out.println(s1 == s3); // what if there is a variable involved? Then it is // computed at runtime and no interning takes place String sub = "he"; String s4 = sub + "llo"; System.out.println(s1 == s4); // by making the "sub" string final, interning again // takes place final String sub2 = "he"; String s5 = sub2 + "llo"; System.out.println(s1 == s5); // you can intern strings yourself to be able to use // == comparisons s4 = s4.intern(); System.out.println(s1 == s4); } }