I don't understand the ouptut of this code. When comparing two strings with same value (not assigned using new
keyword), java returns true. But when I do it using new
keyword and pass the value in the constructor, it prints false.
But when I use new
keyword and instead of passing the value to the constructor I assign it in the next step. This time it returns true. Why?
class CheckStrings{
String s;
}
public class EQCheckTest {
public static void main(String[] args) {
String a1 = "pune";
String a2 = "pune";
String a3 = new String("pune");
String a4 = new String();
a4 = "pune";
CheckStrings cs = new CheckStrings();
cs.s = "pune";
System.out.println(a1==a2);
System.out.println(a1==cs.s);
System.out.println(a1==a3);
System.out.println(a1==a4);
}
}
OUTPUT:
true
true
false
true
Why a1==a3 false and a1==a4 true?