When I saw the "Java2 Learning Guide" on a few days ago, I solved a problem that I had a previous confusion, I feel that Mouton is open, the same as I think. Questions are as follows. Class newstring {public static void main (string [] args) {string S1 = "java"; string s2 = "java"; string s3 = new string ("java"); if (S1 == S2) System.out. Println ("S1 == S2"); Else System.out.println ("S1! = S2"); if (S1 == S3) {system.out.println ("S1 == S3");} else system .out.println ("s1! = s3");}}
Results of the:
S1 == S2S1! = S3 I have always thought that Java opened a special area in memory in memory, and if so String S2 = "Java"; see if there is existing in this area The same String object, if there is, the reference variable S2 points to it. "Java2 Learning Guide" This book verifies my thoughts.
Excerpt from book reads as follows: Important Facts About Strings and MemoryIn this section we'll discuss how Java handles string objects in memory, and some ofthe reasons behind these behaviors.One of the key goals of any good programming language is to make efficient useof memory . As applications grow, it's very common that String literals occupy largeamounts of a program's memory, and that there is often a lot of redundancy withinthe universe of String literals for a program. To make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool." whenthe compiler encounters a String literal, it checks the pool to see if an identical Stringalready exists. If a match is found, the reference to the new literal is directed to theexisting String, and no new String literal object is created. (The existing Stringsimply has an additional reference.) Now we can start to see why making Stringobjects immutable is such a good idea. If several reference variables refer to the same String WITHOUT EVEN KNOWING IT, IT WOULD BE VERY BAD INY OF THEM CHANGETHE STRING'S VALUE.YOU Might Say, "Well That's All Well and Good, but what if someone overrides thestring class functionality;