Classic problems with Java string objects

Source: Internet
Author: User
Tags java se

public class Stringtest {public static void main (string[] args) {String stra = "abc"; String StrB = "abc"; String strc = new String ("abc"); System.out.println (Stra = = StrB);//truesystem.out.println (stra = "abc");//truesystem.out.println (STRC = "abc");// FalseSystem.out.println (Stra = = STRC);//falsesystem.out.println (Stra.equals (STRC));//truesystem.out.println ( Strb.equals (STRC));//truesystem.out.println (Strc.intern ());//abcsystem.out.println (Stra = = StrC.intern ());// TrueSystem.out.println (Stra.hashcode ());//96354system.out.println (Stra.hashcode () = = Strc.hashcode ());//true}}

Make a basic description of the heap memory and stack memory issues. The data structures of heaps and stacks are not explained here. When using memory in the Java language, stack memory mainly holds the following: basic data types and object references, while heap memory stores objects, stack memory faster than heap memory. summed up in a sentence is: referencing the stack while the object is in the heap.
There are two kinds of comparisons in java, = = = (judging if the object reference is the same) and the Equals () method, Equals () is the method of the object class, and the Equals () method defined in the object class is implemented as follows:

public boolean equals (Object obj) {     return (this = = obj);       }

  The string class overrides the Equals () method, altering the principle that these types of objects are equal, that is, the principle of determining whether an object is equal depends on whether the contents of the two are equal.
To understand the above, let's say string,the nature of the string class is the character array char[], followed by the string class is final, is not inheritable, this may be ignored by most people, again string is a special package type, You can assign a value directly when using string, or you can create an object with new, but the implementation mechanism is different. There is also the concept of a string pool in which the Java runtime maintains a string pool in which string objects are not duplicated, created, or dropped. The string pool is not a heap and stack, but rather belongs to a constant pool (which should be in the method area).

The real meaning of the above code is analyzed below

String stra = "abc"; String StrB = "abc";

The real meaning of the first sentence is to create an object "ABC" in the string pool and then refer to the object "ABC" in the pool when stra. The second sentence executes, because "ABC" already exists in the string pool, so it is no longer created, then STRA==STRB returns True to understand. strb== "ABC" must be correct, there is only one "ABC" in the string pool, and Stra and StrB all point to "ABC" in the pool, that's the truth.

String strc = new String ("abc");

This is a hot issue for Java SE, which is known to create 2 string objects alone, and based on the above statement, only creates a strc reference in the stack memory, creates a string object on the heap memory, the content is "ABC", and Strc points to the first address of the heap memory object.
The following is strc== "abc" problem, obviously not, "ABC" is the object in the string pool, and str2 points to the heap memory of the string object,= = To determine the address , must not wait.
Stra.equals (STRC), this is right, as stated earlier, the equals of the string class overrides the Equals () method of the object class, which is actually determining whether the content is the same.
The following is the Intern () method, which in the Javadoc document describes the Intern () method: Returns a normalized representation of a string object. How do you understand this sentence? The process is actually doing this: The method now looks in the string pool for an object, and there is a reference to the object in the string pool that is returned.
In this case, the string pool exists "ABC", then the call to the Intern () method returns the "ABC" object reference in the pool, and the stra/strb are identical, and STRC is different, because strc points to the heap memory.
The Hashcode () method is a hash code that returns the contents of a string, since the content is the same, the hash code must be the same, then they are equal, this is easy to understand.

Take another look at the following example

public class Test {private static String str = "abc";p ublic static void Main (string[] args) {String str1 = "a"; String str2 = "BC"; String Combo = str1 + str2; System.out.println (str = = combo);//falsesystem.out.println (str = = Combo.intern ());//true}}

This example is used to illustrate that when using the + connection string, the object is actually created in the heap content, then combo points to the space header address of the heap memory store "ABC" string, obviously Str==combo is wrong, and str==combo.intern () is correct, There is also "ABC" in the string pool, which returns directly, and Str also points to the "ABC" object in the string pool. This example shows that any re-modification of the string is a reallocation of memory space, which makes the string objects non-intrusive. That is, the contents of the string once the build is immutable, until a new object is generated.
At the same time the problem comes, using the + connection string to generate new objects each time, and is on the heap memory, and heap memory speed is relatively slow (relative), then a large number of connection strings directly + is not desirable, of course, a high-efficiency method is required. Java provides stringbuffer and StringBuilder to solve this problem. The difference is that the former is thread safe and the latter is non-thread safe, StringBuilder after JDK1.5. There is no guarantee that safe StringBuilder have higher efficiency than stringbuffer.
Since JDK1.5, when the Java virtual machine executes the string's + operation, the internal implementation is also StringBuilder, previously implemented with StringBuffer.

Transferred from: http://sarin.iteye.com/blog/603684/

Java Constant Pool TechnologyThe constant pool technique in Java, which occurs when an object is needed, can be taken out of the pool (if one is not created in the pool), and it is necessary to create some objects quickly and easily, saving a lot of time when the equality variable needs to be created repeatedly.  A constant pool is actually a memory space, and a constant pool exists in the method area. After the JVM compiler compiles the source program into a class file, the bold code is stored in a subset of the byte classifications. And these bytes are called constant pools. This includes constants in classes, methods, interfaces, and so on, including string constants such as String s = "Java", and for string s = "Java", which can be recognized as the same string when translated into. class, automatically optimized to constants, so if there are multiple strings " Java, they are all referenced from the same string object. That is, string s = "Java" where the "Java" value is determined during the Java Program compilation period. (You can see this Java value in the bytecode file after you open the class file with your UE editor or other text editing tools). This Java exists in a constant pool. Note: A constant pool stores only literal string values and does not store symbol references. A string created at run time has a separate memory address, so it is not referenced from the same string object. The Intern () method of string finds whether there is a equal equal string in the constant pool, and if so, returns a reference, without adding its own string into the constant pool. Note: Just the string part. So there will be 2 copies, the part of the constant pool is privately owned and managed by the string class, and its share continues to be used by the object life cycle.  string s = new String ("Java"); statement, how many objects are created? "Java" itself is an object in a constant pool, while executing the new String () at run time, copying an object from the constant pool into the heap and handing the reference of the object in the heap to S hold.  So this statement creates 2 string objects. The string class is also a much used class in Java, and also implements the technique of constant pooling for the convenience of creating a string object. The test code is as follows :
public class Test{public static void Main (string[] args) {//s1,s2 is located on the stack in a different space string s1=new string ("Hello"); String S2=new string ("Hello"); System.out.println (S1==S2);//Output FALSE//S3,S4 is located in the same space in the pool string s3= "Hello" strings4= "Hello"; System.out.println (S3==S4);//Output True}}

  

Strings created with new string () are not constants and cannot be determined at compile time, so the strings created by new string () are not placed in the constant pool, they have their own address space. The invariance mechanism of the string object (memory) causes a large number of objects to be generated when the string strings are modified, because a new string is generated each time the strings are changed. In order to use memory more efficiently, the constant pool encounters a string string at compile time, it checks to see if the same string string already exists within the pool, and if found, points the reference to the existing string object without creating any new string constant object. Not found to create new again. So any modification to a string object will result in a new string object, which still exists and waits for garbage collection. Code: String A = "test"; String b = "Test"; String B = a + B "Java", and A, b to a constant value in the constant pool "text", b=b+ "Java" after the first point to a constant, the content is "test" by the B + "Java" operation, the value pointed before B does not change, But at this point B does not point to the original variable value, but points to another string variable, the content is "text Java". The original variable still exists in memory, but the B variable no longer points to it. eight basic types of wrapper classes and object poolsMost of the basic types of wrapper classes in Java implement the constant pool technique, which is byte,short,integer,long,character,boolean, and the other two types of floating-point wrapper classes are not implemented. In addition byte,short,integer,long,character these 5 types of integer wrapper classes can only be used when the corresponding value is less than or equal to 127 to use the constant pool integer a = new integer (+); integer b = new integer (128); ask you again at this time, what is the result of the output? You know it's false. If you change this number to 127, then execute: Integer a = 127;integer B = 127; System.out.println (A = = B); As a result: true when comparing objects, it is best to use equals, which is easy to control for your own purposes. This leads to Equals () and ==,equals compare the string literal, which is the comparison content, = = comparison reference. Transferred from: http://www.cnblogs.com/dapeng111/p/3530542.html

Instance Code

public static void Main (String args[])      {          string s1 = "a";          String s2 = "B";          String s3 = "AB";                    String S4 = "AB";          System.out.println ("S3==s4?") + (S3==S4));            String S5 = "a" + "B";          System.out.println ("S3==s5?") + (S3==S5));                    String s6 = s1+s2;          System.out.println ("S3==s6?") + (S3==S6));                    String s7 = new String ("AB");          System.out.println ("S3==s7?") + (S3==S7));                    Final String s8 = "a";           Final String S9 = "B";          String S10 = s8 + S9;          System.out.println ("S3==s10?") + (S3==S10));          }  

The above code parsing:

S3 and S4 According to the concept of string they all point to the address within the same buffer pool, so the result is true

S3 and S5 because the addition of two is a constant, the compiler will optimize the s5= "a" + "B" to s5= "AB". So the result is also true.

S3 and S6 because the two variables are added so that the compiler cannot optimize, S1+S2 is equivalent to (new StringBuilder (string.valueof)). S1 (Append). toString (); At run time, Instead of pointing to "AB" in the buffer pool, there will be a new allocation of the string address space. So the result is false.

S3 and S7, according to the buffer pool definition in new when the actual allocation of address space, S7 Point to the new allocated address space so unlike the buffer pool address, so false

S3 and S10, similar to S3 and S5, are the same because the final type compiler is optimized.

The output is:

S3==s4? Trues3==s5? Trues3==s6? Falses3==s7? Falses3==s10? True

  

There are a number of ways to create strings, summed up in three categories:

First, create a string using the new keyword, such as string S1 = new String ("abc");

Second, direct designation. For example, string s2 = "abc";

Third, use concatenation to generate a new string. For example, string s3 = "AB" + "C";

Creation of a String object

The creation of string objects is also very important, the key is to understand its principle.

Principle 1: when using any way to create a string object s, the Java runtime (the running JVM) will hold this x in the string pool to find if there is a string object of the same content, if not, create a string s in the pool, otherwise, not add in the pool.

Principle 2: In Java, whenever you use the New keyword to create an object, you must create a new object (in the heap or stack area).

Principle 3: Creating a String object using direct designations or concatenation with a pure string only checks the string in the maintenance string pool without creating one in the pool. However, the string object will never be created in the stack area again.

principle 4: Creating a String object with an expression containing a variable will not only examine the maintenance of the string pool, but also create a string object in the stack area.

Turn from: Network

Classic problems with Java string objects (GO)

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.