String and StringBuilder

Source: Internet
Author: User

String:

Str.length (), Str.indexof (), Str.lastindexof (),

Str.substring (), Str.trim (), StartsWith (), EndsWith (),

Str.touppercase (), toLowerCase ()

String.valueof (Other types)

StringBuilder:

Builder.tostring (), append (),

Insert (), delete (), replace (), reverse (),

--------------------------------Satin-separated---------------------------------------


String Basic operation
String and its common APIs

1. String is an immutable object

Since strings are widely used in real-world development, the phenomenon of creating a string object frequently occurs when a string is used frequently, and Java uses an optimization method for the use of the string so that the Stirng object is immutable, and once created in memory, the content cannot change. To change the contents of a string, a new object is created. This is done to minimize the overhead of system resources by reusing strings of the same content to the maximum extent possible.

Strings are reference types that are basically objects
Java.lang string using the final decoration cannot be modified
Once the content is changed, a new object is created
Strings that you reference can be re-assigned

2. String constant Pool
The JVM has a restriction on strings, so that strings are used as immutable objects so that they can be reused. In fact, when we initialize a string by literal, constant, the JVM first starts with the Chang of the string (a memory area maintained within a JVM, which is used to hold a string object that has already been created), and the object that is used to hold the string is present, and if it exists, it is directly referenced. If it does not exist, create the string object and store it in a constant pool, and then reference it. Because the string content cannot be changed, we can safely reuse them.
A string is an immutable object

Java caches only direct quantities (literals) or constants

1  2  Public classTestStringDemo1 {3     /**4 * Test constant pool5      */6      Public Static voidMain (string[] args) {7String str1 = "Hello";8String str2 = "Hello";9String STR3 =NewString ("Hello");TenSystem.out.println (str1==str2);  OneSystem.out.println (str1==STR3); A      -     } -}

Double equals problem
Reference type Comparison
Used to determine if the reason for the same object: is the address
equals is used to determine whether the object content is the same

3. Memory encoding and length

Java store each character is saved with 2 bytes, using Unicode encoding. And any character, whether English or Chinese, has a length of 1. So the length of the string is the number of characters in the string.

General Chinese two bytes English one byte
String Unicode encoded in memory each character occupies two bytes regardless of Chinese or English or punctuation

Str.length ()

Str. IndexOf ("can") where the string first appears
Overload
Str4.indexof ("Can", 6); Search starting from sixth

Str. LastIndexOf() where the string last appears


substring Cutting strings

There is a small feature in the JAVAAPI, which usually uses 2 digits to denote a range with a head that does not contain a tail.


Str.substring (11, 17);
You can write it like that.
Str.substring (Str.indexof (".") +1, Str.lastindexof ('. '));


Str.substring (11); Start from the specified position to the end

Nesting intercepts to the point.

String str = "Myhh.jpg"= str.substring (0, Str.indexof ('. ') )); System.out.println (sub);
String userName = " Good man ";
/**          * string trim ()         * Removes whitespace         on both sides of the string */         System.out.println (Username.trim ( ));     = "Thinking in Java";     /**      startsWith (sting str)     * Determines whether a string starts with a given string     * Boolean endsWith (String str     ) */      System.out.println (str6.endswith ("java"));    }

Aaa.doc
determine file type

    /*** Sting touppercase () * Sting tolowercase () * Convert the English part of the string to lowercase*/String STR7= "I like Java";     System.out.println (Str7.touppercase ()); when ignoring case checking, use the /*** Convert other types to strings * Sting has several overloaded methods valueOf (other types of data) **/     DoublePi =3.1415926; BooleanFlag =true; intValue =123; Char[] chararr={' A ', ' B ', ' C ', ' d ', ' e ', ' F '}; String Str8=pi+ "";//First Way: number + str = stringString STR9 =flag+ "";//The true of this time is the string.//The second kind of valueOfSystem.out.println (string.valueof (pi)); }

StringBuilder and its common APIs

1. StringBuilder Package Variable string

We have learned from the string class that it is an immutable object, so the creation of new objects is thrown whenever the content is modified. So when we have a need to frequently modify the string, this does not only not reduce the memory overhead, the return will increase the memory overhead. For this purpose Java provides us with a class specifically designed to modify the contents of a string: StringBuilder.
The class encapsulates a mutable string, in other words, when we need to change the contents of the string, we do not create a new object, but rather modify it on the basis of the original object. This reduces the overhead of memory.
Use the StringBuilder class when the string is frequently modified

StringBuffer Thread Safety
StringBuilder the same as the content of both.

         /*** Classes used to frequently modify strings*/     //an empty string created using the parameterless construction methodStringBuilder Builder=NewStringBuilder (); Builder=NewStringBuilder ("Programing Language:"); /*** * Stingbuilder is not a string * just used to make frequent changes to the string, you can save unnecessary memory overhead * To convert the content represented by StringBuilder to a string * The ToString () method that can call it*/             /** Append a new string to the end of the string equivalent to the string of the + operation * Stringbuilder.append (String str) return value is still StringBuilder * programing Language: Java*/Builder.append ("Java").append (", PHP");      //str+ "Java" append inside whatever the base type is converted to a string | | Returns to itself all can be writtenString Str10=Builder.        toString ();    System.out.println (STR10); 

 /**   * want to become a string * insert PHP * StringBuilder            Insert (int index,string str) *  */   StringBuilder builder1  = new  StringBuilder ("Javacppc#objective-c" ); Builder1. insert (  9, "PHP"                 );          System.out.println (Builder1.tostring ()); }
 /**   * Test Delete part of a string * Delete java * Stringbu Ilder Delete (int from, int end) * With header does not contain tail  */  StringBuilder builder1  = new  StringBuilder ("Javacppc#objective-c"        ); Builder1.delete (  9, one                 ) ; System.out.println (Builder1.tostring ());  
 /**   * allow partial content to be replaced * * StringBuilder Rep Lace (int from, int end,string str) * includes header without tail  */  StringBuilder builder1  = new  StringBuilder ("Javacppc#objective-c"        ); Builder1. replace (  9, One, "AB"                 );           System.out.println (Builder1.tostring ()); 
    /**      *  Flip String     *  StringBuilder     Reverse ()*/new             StringBuilder ("Shanghai tap water from the Sea");        Builder1. Reverse ();                System.out.println (Builder1.tostring ());         }

String and StringBuilder

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.