There are two interview questions about the difference between the String nominal value object and the object created by the constructor = and equals.
Interview Question 1:
Package common object _ String; public class StringDemo4 {public static void main (String [] args) {String s1 = new String ("hello "); string s2 = new String ("hello"); System. out. println (s1 = s2); // falseSystem. out. println (s1.equals (s2); // trueString s3 = new String ("hello"); String s4 = "hello"; // This constant value System is available in the method area. out. println (s3 = s4); // falseSystem. out. println (s3.equals (s4); // trueString s5 = "hello"; String s6 = "hello"; System. out. println (s5 = s6); // trueSystem. out. println (s5.equals (s6); // true }}
Interview Question 2:
Package common object _ String; public class StringDemo5 {public static void main (String [] args) {String s1 = "hello"; String s2 = "world "; string s3 = "helloworld"; System. out. println (s3 = s1 + s2); // false. out. println (s3.equals (s1 + s2); // trueSystem. out. println (s3 = "hello" + "world"); // true (because "hello" and "world" are constants, so first splice and then find the constant after splicing, and find that there are, s3 so equal) System. out. println (s3.equals ("hello" + "world"); // true // check the source code through decompilation. We know that the processing is completed here. // System. out. println (s3 = "helloworld"); // System. out. println (s3.equals ("helloworld "));}}
/*
* Conclusion:
* If the string is a variable addition, open the space first and then splice it (the address is definitely different when the space is opened)
* If a string is a constant addition, it is first added and then found in the constant pool. If yes, it is directly returned; otherwise, it is created.
We can use the Java decompilation tool XJad to figure out the cause.
*/