String,StringBuffer,StringBuilder What's the difference?String Why is it immutable?

String Is a string constant,StringBuffer andStringBuilder Is a string variable.StringBuffer Is thread safe,StringBuilder Non thread safe. say concretelyString Is an immutable object, Each modificationString The object is actually a new object of innovation, And point the reference to the new object. Efficiency is very low..StringBuffer It is variable. That is, each modification is only for itself, In most casesString Efficient,StringBuffer Guaranteed synchronization(synchronized), So thread safety.StringBuilder Synchronization not implemented, So non thread safe. But efficiency should be better thanStringBuffer high.StringBuffer It is better to specify the capacity when using, This will be faster than unspecified capacity30%-40%, Even better than theStringBuilder Faster.

String Common methods in

1 Find a character in a string
publicchar charAt(int index)// Returns the character at the specified position in the string; Note that the first character index in the string is0, The last one islength()-1.

String str = new String("asdfzxc");

2 Get the corner mark

 Int indexOf(char c)  for example:String s=”Java”;    Inta=s.indexOf(a);

3 judge

 1: Whether a string contains a string

booleancontains(str)// Determine whether the source string containsstr String and returnboolean value

                                    for example:Stringstr=”My love Java”;



2: Whether the string has content

  booleanisEmpty()                 for example:booleanb=str.isEmpty();

3: Whether the string starts with the specified content

  booleanstartsWith(str)           for example:booleanb=str.startsWith(“My”);

4: Whether the string ends with the specified content

   booleanendsWith(str);           Usage as above

5: Judge whether the content is the same

  boolean equals(str)      //String Class rewritingObject Classequals Method, This method is used to determine whether the content of the string is the same instead of the address

                                   for example: Stringstr1=”Java”;



6: Judge whether the content is the same, And ignore case

  BooleanequalsIngoreCase(str)     Usage is the same as above.

4 Extract substring
useString Classsubstring Method to extract substrings from a string, This method has two common parameters:
1)publicString substring(int beginIndex)
// The method frombeginIndex Position up, Takes the remaining characters from the current string and returns them as a new string.
2)publicString substring(int beginIndex, int endIndex)
// The method frombeginIndex Position up, Fetch from current string toendIndex-1 Position as a new string
1 String str1 = new String("asdfzxc"); 2 String str2 = str1.substring(2);
//str2 = "dfzxc" 3 String str3 = str1.substring(2,5);//str3 = "dfz"
5 string comparison
1)public int compareTo(StringanotherString)
// This method is to compare the size of the string contents in dictionary order, Indicates the size relationship between the current string and the parameter string by the returned integer value. Returns a positive integer if the current object is larger than the parameter, Negative integer, Equal return0.
2)public int compareToIgnore(StringanotherString)// AndcompareTo Similar method, But ignore case.
3)public boolean equals(ObjectanotherObject)
// Compare the current string with the parameter string, Return when two strings are equaltrue, Otherwise returnfalse.

6 Case conversion of characters in strings
1)public String toLowerCase()// Returns the new string after converting all characters in the current string to lowercase
2)public String toUpperCase()// Returns a new string that converts all characters in the current string to uppercase
1 String str = new String("asDF"); 2 String str1 = str.toLowerCase();//str1 =
"asdf" 3 String str2 = str.toUpperCase();//str2 = "ASDF"
7 Replacement of characters in strings
1)public String replace(char oldChar, charnewChar)
// Using charactersnewChar Replace all in the current stringoldChar character, And returns a new string.
2)public String replaceFirst(String regex,String replacement)
// This method uses charactersreplacement Replace the first and string encountered in the current string with the contents ofregex Matching substring, New string should be returned.
3)public String replaceAll(String regex,String replacement)
// This method uses charactersreplacement Replace all and strings encountered in the current string with the contents ofregex Matching substring, New string should be returned.
1 String str = "asdzxcasd"; 2 String str1 = str.replace('a','g');//str1 =
"gsdzxcgsd" 3 String str2 = str.replace("asd","fgh");//str2 = "fghzxcfgh" 4
String str3 = str.replaceFirst("asd","fgh");//str3 = "fghzxcasd" 5 String str4
= str.replaceAll("asd","fgh");//str4 = "fghzxcfgh" String delimitation String[] split(String
str)// takestr String decomposition as separator, The decomposed word string is returned in the string array. 1 String str = "asd!qwe|zxc#"; 2
String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] =
8 Conversion between string and basic type
1, String to base type
java.lang In bagByte,Short,Integer,Float,Double Call method of class:
1)public static byte parseByte(String s)
2)public static short parseShort(String s)
3)public static short parseInt(String s)

String basic type, asint short dobule The data in the string must be a number, Otherwise, an exception will occur
4)publicstatic long parseLong(String s)
5)publicstatic float parseFloat(String s)
6)publicstatic double parseDouble(String s)
for example:
1 int n = Integer.parseInt("12"); 2 float f = Float.parseFloat("12.34"); 3
double d = Double.parseDouble("1.124");
9 Convert base type to string type
String Class providesString valueOf() Release method, Convert as base type to string type.
1)static String valueOf(char data[])
2)static String valueOf(char data[], intoffset, int count)
3)static String valueOf(boolean b)
4)static String valueOf(char c)
5)static String valueOf(int i)
6)static String valueOf(long l)
7)static String valueOf(float f)
8)static String valueOf(double d)
for example:
1 String s1 = String.valueOf(12); 2 String s1 = String.valueOf(12.34);
10 Array related methods

Return type Method name function byte[] getBytes() Convert a string to a byte arraychar[] toCharArray() Convert a string to a character array
String[]split(String) Splits a string according to the specified content

isEmpty: Judge whether it is empty

public boolean isEmpty()

if and only if length() <> by 0
Return time true.



StringBuffer Usage

StringBuffer Principle

StringBuffer Inherited abstract classAbstractStringBuilder, stayAbstractStringBuilder In class, There are two fieldschar[] Typevalue andint Typecount, In other words,StringBuffer Is essentially a
Character array:


S in useStringBuffer When, Habitual imageString And initialize him to

[java] view plain <>copy

StringBuffer result = null;  

Result warnings:Null pointer access:The variable result can only be null at this location

Error reporting after operation, Just realizeStringBuffer andString There are still many differences, I've ferried some materials and sorted them out, Share.

The following is reproduced from 

StringBuffer Class sumString equally, Also used to represent strings, Just becauseStringBuffer AndString Different, thereforeStringBuffer During string processing, Do not generate new objects, Better than memory usageString class.

   So in actual use, If you often need to modify a string, For example, insert, Delete and other operations, UseStringBuffer Better fit.

stayStringBuffer There are many andString Class like method, These methods are functional andString The functions in the class are exactly the same.

But the most significant difference is, aboutStringBuffer Every modification of an object changes the object itself, This is the sum ofString Class biggest difference.

In addition,StringBuffer Is thread safe,
The concept of thread will be introduced in the following chapters, So it can also be used conveniently in multithreaded programs, But the execution efficiency of the program is relatively slow.

1,StringBuffer Object initialization

StringBuffer Object initialization is not likeString Class initialization is the same,Java Provided with special syntax, In general, the construction method is used for initialization.

for example:

StringBuffer s = new StringBuffer();

This initializesStringBuffer Object is an empty object, It's my mistake.

If you need to create aStringBuffer object, You can use the:

        StringBuffer s = new StringBuffer(“abc”);

This initializesStringBuffer The content of an object is a string”abc”.

It should be noted that,StringBuffer andString Belong to different types, You cannot cast directly, The following code is all wrong:

        StringBuffer s = “abc”;              // Assignment type mismatch

        StringBuffer s = (StringBuffer)”abc”;    // No inheritance, Unable to perform forced rotation

StringBuffer Object andString The code for mutual conversion between objects is as follows:

        String s = “abc”;

        StringBuffer sb1 = newStringBuffer(“123”);

        StringBuffer sb2 = newStringBuffer(s);   //String Convert toStringBuffer

        String s1 =sb1.toString();             //StringBuffer Convert toString

        2,StringBuffer Common methods of

StringBuffer The methods in class mainly focus on the changes of strings, For example, additional, Insert and delete, etc, This is also true.StringBuffer andString Main differences of class.

a,append Method

        public StringBuffer append(boolean b)// stayString Of use+ Number connection string

The function of this method is to append content to the currentStringBuffer End of object, String like connection. After calling this method,StringBuffer The content of the object also changes, for example:

                 StringBuffer sb = newStringBuffer(“abc”);


          Then objectsb The value of becomes”abctrue”.

Use this method to connect strings, Will compareString More content saving, For example, apply to databaseSQL Connection of statements, for example:

                  StringBuffer sb = new StringBuffer();

                  String user = “test”;

                  String pwd = “123”;

                  sb.append(“select * from userInfo where username=“)


                   .append(“ and pwd=”)


          Such objectsb The value of is a string“select* from userInfo where username=test and pwd=123”.

It's not on one level at all, I hope you will keep in mind! A large number of string connections must useappend
() Method, The reason is very simple, String connection needs to create a new string object every time to save the new string, such...... You know!

b,deleteCharAt Method

        public StringBuffer deleteCharAt(int index)

The function of this method is to delete characters in the specified position, The rest is then formed into a new string. for example:

        StringBuffer sb = new StringBuffer(“Test”);

        sb. deleteCharAt(1);

The function of this code is to delete a string objectsb The index value in is1 Character, That is, delete the second character, The rest of the content forms a new string. So objectsb The value changes to”Tst”.

There is a similar functiondelete Method:

        public StringBuffer delete(int start,int end)

The function of this method is to delete all characters within the specified range, Containstart, Does not containend Interval of index value. for example:

        StringBuffer sb = new StringBuffer(“TestString”);

        sb. delete (1,4);

The purpose of this code is to delete the index value1( Include) To index value4( Barring) All characters between, The remaining characters form a new string. Then objectsb The value is”TString”.

c,insert Method

        publicStringBuffer insert(int offset, boolean b)

        The purpose of this method is toStringBuffer Insert content in object, Then form a new string. for example:

                  StringBuffersb = new StringBuffer(“TestString”);


The purpose of this sample code is tosb Index value4 Insert atfalse value, Form a new string, After executionsb The value is”TestfalseString”.

d,reverse Method

        publicStringBuffer reverse()

The purpose of this method is toStringBuffer Reverse content in object, Then form a new string. for example:

        StringBuffer sb = new StringBuffer(“abc”);


After reversal, objectsb Content in will become”cba”.

e,setCharAt Method

                           public void setCharAt(int index, char ch)

                             The function of this method is to modify the index value of the object toindex The character in position is a new characterch. for example:

                                    StringBuffer sb = new StringBuffer(“abc”);


                             Then objectsb The value of becomes”aDc”.

f,trimToSize Method

         publicvoid trimToSize()

The purpose of this method is toStringBuffer Object to the same length as the string, Reduce space waste.

          in short, In actual use,String andStringBuffer Each has its own advantages and disadvantages, According to the specific use environment, Select the corresponding type to use.

StringBuilder Detailed explanation

StringBuilder andStringBuffer equally, All inherited from abstract classesAbstractStringBuilder class, It's also a variable character sequence.StringBuilder andStringBuffer Very similar, There are even compatible onesAPI, However,StringBuilder Not thread safe, This is the sum ofStringBuffer Main differences.StringBuilder The hierarchy of is as follows:

StringBuilder Class is designed to replace without multithreading securityStringBuffer Class. If multithreading security is not required in a program, Recommended useStringBuilder class, It's faster because there's no synchronization.

StringBuilder andStringBuffer equally, The main operations areappend andinsert etc..

2,StringBuilder principle

StringBuilder Principle andStringBuffer equally, The difference isStringBuilder No need to consider thread safety. See another chapter for specific principles
StringBuffer Detailed explanation <>.


3, common method

StringBuilder Common methods andStringBuffer Same.. Listed below: