I am beginning to learn Java,so please pardon if the question seems silly, I was going through some online examples.
I found a String question, should not the output be true ?
As I am comparing two strings which are equal.
public class HelloWorld{
public static void main(String []args)
{
String morning2 = new String("Morning");
System.out.println("Morning" == morning2);
}
}
Similarly for this program, should not this print True
public class HelloWorld{
public static void main(String []args)
{
String str1 = new String("Paul");
String str2 = new String("Paul");
System.out.println(str1 == str2);
}
}
But for this program, it prints true.
public class HelloWorld{
public static void main(String []args)
{
String str3 = "Harry";
String str4 = "Harry";
System.out.println(str3 == str4);
}
}
Can anyone explain why is there difference in output ?
I have seen this question and answer How do I compare strings in Java? but It does not really fit the explanation.