First, put the problem out and look at the code first.
String a = "ab";
String b = "a" + "b";
System.out.println((a == b));
What will the print result be? Similar to such a problem, someone has tested me, I also take to test others (good play, we can also ask people to play), the general answer will be the following:
1.true
"A" + "B" result is "AB", so that a,b are "AB", the same content so "equal", the result is true
General Java New Person answer.
2.false
"A" + "a" will generate a new object "AA", but this object and string a = "AB"; different, (a = = B) is the comparison object reference, so not equal, the result false
The usual answer to this is that a Java string has a certain understanding.
3.true
String a = "AB"; a new object "AB" was created, followed by string B = "a" + "B", and the result b= "AB", where no new object was created, and instead the previous "AB" object was fetched from the JVM string constant pool. So A,b has a reference to the same string object, two references are equal, and the result is true.
Can answer this answer, the basic is already a master, the Java in the string mechanism more understanding.
Unfortunately, the answer is not accurate enough. Or, at all, there is no run-time calculation of B = "a" + "B"; this operation. In fact, only string B = "AB" is running;
The 3 point of view is appropriate to explain the following:
String a = "ab";
String b = "ab";
System.out.println((a == b));
If string b = "a" + "B" is executed at run time, the 3 point of view is unexplained. The two string added to the runtime produces a new object. (This is explained later in this article)
4.true
Here is my answer: Compile optimization + 3 processing method = Last True
String B = "a" + "B"; the compiler takes this "a" + "B" as a constant expression, optimizes at compile time, and directly takes the result "AB" so that this problem degrades
String a = "ab";
String b = "ab";
System.out.println((a == b));
And then according to the 3 explanation, get the result true
One of the questions here is that string is not a basic type, like
int secondsofday = 24 * 60 * 60;