I want to understand the == operator in JAVA;
String name = "Object Oriented";
String str1 = "Object";
String str2 = "Object";
String str3 = new String("Object");
String str4 = name.substring(0,6);
String str5 = name.substring(0,6);
String str6 = "Obj" + "ect";
System.out.println(str1 + "==" + str2 + ": " + (str1 == str2));
System.out.println(str1 + "==" + "Object" + ": " + (str1 == "Object"));
System.out.println(str1 + "==" + str6 + ": " + (str1 == str6));
System.out.println(str1 + "==" + str3 + ": " + (str1 == str3));
System.out.println(str1 + "==" + str4 + ": " + (str1 == str4));
System.out.println(str4 + "==" + str5 + ": " + (str4 == str5));
The output is weird;
Object==Object: true
Object==Object: true
Object==Object: true
Object==Object: false
Object==Object: false
Object==Object: false
In the Deitel How to Program Java book, it says;
To conserve memory, Java treats all string literals with the same contents as a single String object that has many references to it.
So, str1 and str2 are individual string literals, and Java treats them as a single object. Similarly, str6 is the same content.
The "str3" is a new object, it is the supposed output (false).
But, I don't understand the last two. What is the difference between "str4" and "str6", "str2" and "str5"?
Is the "str1" a variable and the other ones are objects?
I know "equal()" method. I know the difference between two methods.
this is not the same question with this