Equality comparison of strings in Java

Source: Internet
Author: User

First, post the test case:

1 Package test;2 3 import org.junit.Test;4 5 /**6 * Created by Administrator on 2015/9/16.7  *8  */9  Public classteststring {Ten  OneString str1 ="Hello Quanjizhu";//if not in the string pool, create a new object and put it in the string pool AString str2 =str1+"haha";//because of the string immutable class, it is equivalent to creating a new object -String STR3 =NewString ("Hello Quanjizhu");//Create a new object in the heap -  the     /** - * equals: Compares the values of two string objects for equality - * i.e.: compare content - * Result: True,true +      */ - @Test +      Public voidstr_equal () { ASystem. out. println (Str1.equals (str2));//true atSystem. out. println (Str1.equals (STR3));//true -     } -  -     /** - * = =: Compares the points of memory addresses of two string objects for equality.  - * Result: False,false in      */ - @Test to      Public voidStr_c () { +System. out. println (STR1==STR2);//false -System. out. println (STR1==STR3);//false the     } *  $     /**Panax Notoginseng * Creation of String - * 1.String A = new string ("AAA") creates a string object on the heap the * 2.String A = new string ("AAA") creates a string object on the heap + * 3.String c = "AAA"; Find AAA in string pool, create a new object on the heap and put in string pool A * 4.String d = "AAA"; D and C point to a common object the      */ + @Test -      Public voidstr_create () { $String A =NewString ("AAA"); $String B =NewString ("AAA"); -String C ="AAA"; -String d ="AAA"; theSystem. out. println (A==B);//false -System. out. println (A.equals (b));//trueWuyiSystem. out. println (A==c);//false theSystem. out. println (A.equals (c));//true -System. out. println (C==d);//true WuSystem. out. println (C.equals (d));//true -  AboutA=a.intern ();//put the content of a into the string pool, if present in the pool, directly return to the address in the pool, if not present, put, the address of a in this test case will eventually become the address of C $System. out. println (A==c);//true -System. out. println (A.equals (c));//true -     } -  A  +}

Reproduced below: http://blog.sina.com.cn/s/blog_4ef2568301014xmd.html

1. First describe the methods for comparing three string objects:
(1) equals: Compares the values of two string objects for equality. For example:

1 String str1 = "Hello Quanjizhu"; 2 String str2 =str1+ "haha"; 3 New String ("Hello Quanjizhu"); 4 5  6

The output is true.

(2) = =: Compares the point-to-memory addresses of two string objects for equality. For example:

1 String str1 = "Hello Quanjizhu"; 2 String str2 =str1+ "haha"; 3 New String ("Hello Quanjizhu"); 4 5  6

The output is false.

3. Principle
To understand how string works in Java, it's important to be clear: string is a non-mutable class (immutable). What is a non-mutable class? In short, an instance of a non-mutable class cannot be modified, and the information contained in each instance must be provided at the time the instance is created and fixed throughout the lifetime of the object. Why does Java want to design string as a non-mutable class? You can ask James Gosling:). But non-mutable classes do have their own advantages, such as a single state, simple object, easy to maintain. Second, this class of object objects is inherently thread-safe and does not require synchronization. In addition, users can share non-mutable objects and can even share their internal information. (see "Effective Java" item 13). The string class is used extensively in Java, even in class files, so it is more appropriate to design it as a simple, lightweight, non-mutable class.
(1) Create.
Well, knowing that string is a non-mutable class, we can learn more about how the string is constructed. To create a Stirng object, there are two main ways of doing this:

1 New String ("abc");    2

Although both statements return a reference to a string object, the JVM handles the two differently. For the first, the JVM immediately creates a string object in the heap and then returns a reference to the object to the user. For the second, the JVM will first look through the string's Equels method in the internally maintained strings pool to see if there is a string object in the object pool, and if so, returns the existing string object to the user. Instead of recreating a new string object in the heap, if the string object is not in the object pool, the JVM creates a new string object in the heap, returns its reference to the user, and adds the reference to the strings pool. Note: When creating an object using the first method, the JVM does not actively place the object inside the strings pool unless the program calls the Intern method of string. Look at the following example:

1 Java Code2String str1 =NewString ("abc");//JVM creates a string object on the heap3  4  //The JVM could not find a string with the value "ABC" in the Strings pool, so5  //creates a string object on the heap and adds a reference to the object to the strings pool6  //There are two string objects on this heap7STIRNG str2 = "abc"; 8  9  if(str1 = =str2) {  TenSystem.out.println ("str1 = = str2");  One}Else{   ASYSTEM.OUT.PRINTLN ("Str1! = str2");  -  -   //The print result is str1! = str2 because they are two different objects on the heap the   -String STR3 = "abc";  -  //at this point, the JVM discovers that an "ABC" object is already in the strings pool because "abc" equels " abc" -  //so directly return the object that str2 points to str3, which means str2 and STR3 are references to the same object +   if(str2 = =STR3) {   -System.out.println ("str2 = = STR3");  +}Else{   ASYSTEM.OUT.PRINTLN ("Str2! = STR3");  at   }   -  //print result str2 = = Str3 - let's look at the following example: -  -  - Java Code inString str1 =NewString ("abc");//JVM creates a string object on the heap -   toSTR1 =Str1.intern ();  + //The program explicitly puts str1 into the strings pool, and intern runs like this: First view strings Pool - //There is no reference to the "ABC" object, no, create a new object in the heap, and then add a reference to the new object to the the //the strings pool. After executing the statement, the string object that the str1 originally pointed to has become a garbage object, and is ready to * //collected by GC.  $  Panax Notoginseng //at this point, the JVM discovers that an "ABC" object is already in the strings pool because "abc" equels " abc" - //so directly return the object that str1 points to str2, which means that str2 and str1 refer to the same object, the //at this point, there is only one valid object on the heap.  +STIRNG str2 = "abc";  A   the  if(str1 = =str2) {   +System.out.println ("str1 = = str2");  -}Else{   $SYSTEM.OUT.PRINTLN ("Str1! = str2");  $  }   -   //The print result is str1 = = str2


Why can the JVM handle string objects like this? is because of the non-variability of string. Since the referenced object never changes once it is created, multiple references do not affect each other when they share an object.


(2) thread connection (concatenation). The
     java programmer should know that the misuse of string's string operators can affect the performance of the program. Where does the performance problem come from? The final analysis is the non-variability of the string class. Since the string object is non-mutable, that is, once the object is created, it cannot change its intrinsic state, but the string operation is obviously to increase the string, that is, to change the internal state of the string, there is a contradiction between the two. What do we do? To maintain the non-variability of a string, you have to create a string object to represent the newly generated string after the string is completed. That is, each execution of a string will result in the creation of a new object, and if the threaded operation is performed frequently, it will result in a large number of objects being created, and performance problems will follow.
     To solve this problem, the JDK provides a mutable companion class for the String class, StringBuffer. With the StringBuffer object, because the class is mutable, the internal data structure is changed only when the thread is connected, and the new object is not created, so the performance is greatly improved. For single-threaded, JDK 5.0 also provides a StringBuilder class that, in a single-threaded environment, uses this class to further improve performance because it does not need to be considered for synchronization issues.

(3) Length of string
We can use the string-connect operator to get a longer string, so how many characters can a string object hold? Viewing the source of a string we can tell that the class string uses domain count to record the number of object characters, and count is of type int, so we can speculate that the longest length is 2^32, which is 4G.
However, when we write the source code, if we use Sting str = "AAAA" to define a string, then the ASCII characters in double quotation marks can only be 65,534. Why is it? Because in the specification of the class file, the Constant_utf8_info table uses a 16-bit unsigned integer to record the length of the string, which can represent a maximum of 65,536 bytes, while the Java class file holds the characters in a Variant UTF-8 format. The null value is represented by two bytes, so only 65536-2 = 65,534 Bytes is left. It is also the reason for variant UTF-8 that if the string contains non-ASCII characters such as Chinese, then the number of characters in the double quotation marks will be less (one Chinese character takes three bytes). If this amount is exceeded, the compiler will error when compiling.


(3) CompareTo: Compares the values of two string objects for equality. For example:

 1  String str1 = "Hello Quanjizhu"  2  String str2 =str1+ "haha" ;  3  string str3 = new  String ("Hello Quanjizhu " 4   System.out.println (Str1.compareto (str2));  6  System.out.println (Str1.compareto (STR3)); 

The output is 0. (if output greater than 0 means str1 is greater than STR2)
The difference between several initialization methods of the 2.String class
(1) String str1 = "Hello Quanjizhu";
First, look in the string pool for any object that has a value of Hello Quanjizhu, and if so, let str1 point directly to the memory address, and if not, re-open the space in the memory heap to str1 and add the Hello Quanjizhu to the string pool.
(2) String str3 = new String ("Hello Quanjizhu");
Each initialization re-opens up space in the memory heap to the new object, not to the string pool, and not to the string pool. Unless the call intern method is displayed.
Str3.interl (); This will add the Hello Quanjizhu to the string pool.
(3)
String str1 = "Hello Quanjizhu";
String str2 = "Hello" + "Quanjizhu";
string str3 = "Hello" + "Quanjizhu", which is optimized to string str3 = "Hello Quanjizhu" at compile time; all str1 and str2 point to the same memory address.
(4)
String var = "Quanjizhu";
String STR4 = "Hello" +var;
What is the result of System.out.println (str1= =STR4)? The output is false, proving the string str4 = "Hello" +var;
The space is redistributed in the memory heap, rather than having the STR4 point to the Var address. Swap a definition method: STR4 = ("Hello" +var4). Intern (); The Intern () method tells the compiler to put this result in the string pool, so System.out.println (str1= = STR4) The output structure will be true;

Equality comparison of strings in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.