Strings in Java

Source: Internet
Author: User

Zen House Moon (http://www.cnblogs.com/yaoyinglong/)

1. The string can be recycled by GC

We said before in the trap of expression "for the direct amount of characters in a Java program, the JVM uses a string pool to protect them: When a string is first used directly, the JVM puts them in a string pool for caching. "Before jdk1.7, hotspot put the string constant pool in the permanent generation, so we said" in general, string objects in the string buffer pool will not be garbage collected ", but jdk1.7 later the hotspot will remove the string constant pool from the permanent generation. So we see the following program, which does not cause a memory overflow:

 Public class stringtest {    publicstaticvoid  main (string[] args) {        List< string> list=New arraylist<string>();         int i=0;          while (true) {            List.add (string.valueof (i+ +). Intern ())     }}}

This code will continue to loop through the jdk1.7, but it will be reported as "Outofmemoryerror:permgen space" error in jdk1.6. This way, the Java string constant pool is returned to the heap memory, accepting garbage collection by the garbage collector.

2.String is immutable.

After creating the good one string, it will no longer be changed, and looking at the JDK document will find that the method that looks like a modified string value in the string class actually creates a completely new string object that contains the modified string content, while the original string object is not moved.

3.String overloaded the "+" operator

Java programmers are not allowed to overload operators.

 Public class stringtest {    publicstaticvoid  main (string[] args) {        String mango = "Mango";        String s= "abc" +mango+ "def" +47;        System.out.println (s);    }}

Use JAVAP to decompile the above code:

E:\program\thinking_in_java\bin\string>javap-c Stringtest.classCompiled from"Stringtest.java" Public classstring. stringtest { Publicstring.    Stringtest (); Code:0: Aload_01:invokespecial #8//Method java/lang/object. " <init> ":() V4:return   Public Static voidMain (java.lang.string[]); Code:0:LDC #16//String Mango2: Astore_13:New#18//class Java/lang/stringbuilder6: DUP7:LDC #20//String ABC 9:invokespecial #22//Method java/lang/StringBuilder. " <init> ":(ljava/lang/string;) V12: Aload_113:invokevirtual #25//Method java/lang/stringbuilder.append:(ljava/lang/string;) Ljava/lang/stringbuilder;16:LDC #29//String def 18:invokevirtual #25//Method java/lang/stringbuilder.append:(ljava/lang/string;) Ljava/lang/stringbuilder;21:bipush -23:invokevirtual #31//Method java/lang/stringbuilder.append:(I) Ljava/lang/stringbuilder;26:invokevirtual #34//Method java/lang/stringbuilder.tostring: () ljava/lang/string;29: astore_230:getstatic #38//Field Java/lang/system.out:ljava/io/printstream;33: Aload_234:invokevirtual #44//Method java/io/printstream.println: (ljava/lang/string;) V37:return}

From the anti-compilation code above, we can clearly see that the compiler uses StringBuilder to optimize our strings by default. This avoids the intermediate garbage generated by stitching directly with the string and the "+" operator. Since the JDK has done a string optimization for us, then we are not taboo Tantric use "+" it? So let's take a look at exactly how well the compiler optimizes for us:

 Public classStringtest { Publicstring implicit (string[] fields) {string result="";  for(inti=0; i<fields.length; i++) {result+=Fields[i]; }        returnresult; }     PublicString Explicit (string[] fields) {StringBuilder result=NewStringBuilder ();  for(inti=0; i<fields.length; i++) {result.append (fields[i]); }        returnresult.tostring (); }     Public Static voidMain (string[] args) {}}

First we look at the first post-compilation function:

 Publicjava.lang.String Implicit (java.lang.string[]); Code:0:LDC #16//String2: astore_23: Iconst_04: Istore_35: Goto 8:New#18//class Java/lang/stringbuilder11: DUP12: Aload_213:invokestatic #20//Method java/lang/string.valueof: (ljava/lang/object;) ljava/lang/string;16:invokespecial #26//Method java/lang/StringBuilder. " <init>":(ljava/lang/string;) V19: Aload_120: Iload_321st: Aaload22:invokevirtual #29//Method java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;25:invokevirtual #33//Method java/lang/stringbuilder.tostring: () ljava/lang/string;28: astore_229:iinc 3, 1 32: iload_3     33: Aload_134: Arraylength35:IF_ICMPLT 8 38: Aload_239:areturn

From the anti-compilation code above, it can be seen that from the 4th to the 32nd line is the for loop body, and we also see that StringBuilder is created in the For loop, that is, each cycle creates a new StringBuilder. Take a look at the second function:

 Publicjava.lang.String Explicit (java.lang.string[]); Code:0:New#18//class Java/lang/stringbuilder3: DUP4:invokespecial #45//Method java/lang/StringBuilder. " <init> ":() V7: astore_28: Iconst_09: istore_3     10:Goto24 13: Aload_214: Aload_115: Iload_316: Aaload17:invokevirtual #29//Method java/lang/stringbuilder.append: (ljava/lang/string;) Ljava/lang/stringbuilder;20: Pop21:iinc 3, 1 24: iload_3     25: Aload_126: Arraylength27:IF_ICMPLT 13 30: Aload_231:invokevirtual #33//Method java/lang/stringbuilder.tostring: () ljava/lang/string;34:areturn

Not only is the code shortened, but the entire method generates a StringBuilder object only outside the For loop.

Summary: Processing a string in a loop is best to create a StringBuilder object yourself and use it to construct the final result, which can be relied upon by the compiler to optimize the string.

4. A trap:
 Public class stringtest {    publicstaticvoid  main (string[] args) {        String  STR1= "abc";        StringBuilder SB=new  StringBuilder ();        Sb.append ("is true? ");        Sb.append (str1+str1.length ());        System.out.println (Sb.tostring ());}    }

What does the compiler do with this code?

 Public Static voidMain (java.lang.string[]); Code:0:LDC #16//String ABC2: Astore_13:New#18//class Java/lang/stringbuilder6: DUP7:invokespecial #20//Method Java/lang/stringbuilder. " <init> ":()V10: astore_211: Aload_212:LDC #21//String is true? 14:invokevirtual #23//Method java/lang/stringbuilder.append:(ljava/lang/string;) Ljava/lang/stringbuilder;17: Pop18: Aload_219:New#18//class Java/lang/stringbuilder22: DUP23: Aload_124:invokestatic #27//Method java/lang/string.valueof: (ljava/lang/object;) ljava/lang/string;27:invokespecial #33//Method java/lang/StringBuilder. " <init> ":(ljava/lang/string;) V30: Aload_131:invokevirtual #36//Method java/lang/string.length: () I34:invokevirtual #40//Method java/lang/stringbuilder.append: (I) Ljava/lang/stringbuilder;37:invokevirtual #43//Method java/lang/stringbuilder.tostring:() ljava/lang/string;40:invokevirtual #23//Method java/lang/stringbuilder.append:(ljava/lang/string;) Ljava/lang/stringbuilder;43: Pop44:getstatic #47//Field Java/lang/system.out:ljava/io/printstream;47: Aload_248:invokevirtual #43//Method java/lang/stringbuilder.tostring:() ljava/lang/string;51:invokevirtual #53//Method java/io/printstream.println: (ljava/lang/string;) V54:return

By the above code we can see that in sb.append (str1+str1.length ()); In this code, the compiler has taken a string that creates a StringBuilder in the stitching brackets, The StringBuilder ToString is then passed to the peripheral StringBuilder.

Conclusion: It is forbidden to use "+" in the Append of StringBuilder. It's even worse if the StringBuilder is in the loop.

Strings in Java

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.