public static void main(String[] args){
one();
two();
three();
}
public static void one() {
String s1 = "hill5";
String s2 = "hill" + 5;
System.out.println(s1==s2);
}
public static void two() {
String s1 = "hill5";
int i =5;
String s2 = "hill" + i;
System.out.println(s1==s2);
}
public static void three() {
String s1 = "hill5";
String s2 = "hill" + s1.length();
System.out.println(s1==s2);
}
Output is
true
false
false
String literals use interning process,then why two() and three() is false.I can understand in case of three() but two() is not clear.but need proper explanation for both cases.
Can someone please explain proper reason?
twowithfinal int i = 5;instead (it will print true instead of false, because nowiis a constant).==to compare strings - it will make your program brittle. This is simply a question of when strings are interned and that depends on the compiler used (inone()) and the JVM used.