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

String Is a string constant ,StringBuffer and StringBuilder Is a string variable .StringBuffer Is thread safe ,StringBuilder Non thread safe . say concretely String Is an immutable object , Every modification String The object is actually a new object of innovation , And point the reference to the new object . Very inefficient .StringBuffer It's variable , That is, each modification is only for itself , In most cases String efficient ,StringBuffer Ensure synchronization (synchronized), So thread safety .StringBuilder Synchronization not implemented , So non thread safe . But efficiency should be better than StringBuffer high .StringBuffer It is better to specify the capacity when using , This will be faster than unspecified capacity 30%-40%, Even better than the StringBuilder It's fast .

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 is 0, The last one is length()-1.

String str = new String("asdfzxc");

2 Get angle sign

 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 contains str String and return boolean value

                                    for example :Stringstr=”My love Java”;


                                    result :true

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);           Use as above

5: Judge whether the content is the same

  boolean equals(str)      //String Class overridden Object In class equals 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)     Same as above

4 Extract substring
use String Class substring Method to extract substrings from a string , This method has two common parameters :
1)publicString substring(int beginIndex)
// The method from beginIndex From position , Takes the remaining characters from the current string and returns them as a new string .
2)publicString substring(int beginIndex, int endIndex)
// The method from beginIndex From position , Fetch from current string to endIndex-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 return 0.
2)public int compareToIgnore(StringanotherString)// And compareTo Method similarity , But ignore case .
3)public boolean equals(ObjectanotherObject)
// Compare the current string with the parameter string , Return when two strings are equal true, Otherwise return false.

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)
// Use character newChar Replace all in the current string oldChar character , And returns a new string .
2)public String replaceFirst(String regex,String replacement)
// This method uses characters replacement Replace the first and string encountered in the current string with the contents of regex Matching substring , New string should be returned .
3)public String replaceAll(String regex,String replacement)
// This method uses characters replacement Replace all and strings encountered in the current string with the contents of regex 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)// take str 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 the bag Byte,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 , as int 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 provides String 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 array char[] 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
Back on true.



StringBuffer Usage of

StringBuffer Principle of

StringBuffer Inherited abstract class AbstractStringBuilder, stay AbstractStringBuilder Class , There are two fields char[] Of type value and int Of type count, in other words ,StringBuffer Is essentially a
Character array :


S in use StringBuffer When , Habitual image String And initialize him to

[java] view plain <>copy

StringBuffer result = null;  

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

Error report after operation , To realize that StringBuffer and String There are still many differences , I've ferried some materials and sorted them out , share .

The following is reproduced from 

StringBuffer Class and String equally , Also used to represent strings , Just because StringBuffer And String Different , therefore StringBuffer During string processing , Do not generate new objects , Better than memory usage String class .

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

stay StringBuffer There are many and String Class like method , These methods are functional and String The functions in the class are exactly the same .

But the most significant difference is , about StringBuffer Every modification of an object changes the object itself , That's with String Class biggest difference .

In addition, due to 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 like String 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 initializes StringBuffer Object is an empty object , It's my mistake .

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

        StringBuffer s = new StringBuffer(“abc”);

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

It should be noted that ,StringBuffer and String 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 Objects and String The code for mutual conversion between objects is as follows :

        String s = “abc”;

        StringBuffer sb1 = newStringBuffer(“123”);

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

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

        2,StringBuffer Common methods of

StringBuffer The methods in class mainly focus on the changes of strings , For example, append , Insert and delete, etc , So is this one StringBuffer and String Main differences of class .

a,append method

        public StringBuffer append(boolean b)// stay String of use + Number connection string

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

                 StringBuffer sb = newStringBuffer(“abc”);


          Object sb The value of becomes ”abctrue”.

Use this method to connect strings , Will compare String More content saving , For example, apply to database SQL 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 objects sb 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 use append
() 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 object sb The index value in is 1 Characters of , That is, delete the second character , The rest of the content forms a new string . So object sb The value of becomes ”Tst”.

There is a similar function delete method :

        public StringBuffer delete(int start,int end)

The function of this method is to delete all characters within the specified range , contain start, Not included end 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 value 1( include ) To index value 4( barring ) All characters between , The remaining characters form a new string . Object sb The value of is ”TString”.

c,insert method

        publicStringBuffer insert(int offset, boolean b)

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

                  StringBuffersb = new StringBuffer(“TestString”);


The purpose of this sample code is to sb Index value of 4 Insert at false value , Form a new string , After execution sb The value of is ”TestfalseString”.

d,reverse method

        publicStringBuffer reverse()

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

        StringBuffer sb = new StringBuffer(“abc”);


After reversal , object sb 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 to index The character in position is a new character ch. for example :

                                    StringBuffer sb = new StringBuffer(“abc”);


                             Object sb The value of becomes ”aDc”.

f,trimToSize method

         publicvoid trimToSize()

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

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

StringBuilder Detailed explanation

StringBuilder and StringBuffer equally , All inherited from abstract classes AbstractStringBuilder class , It's also a variable character sequence .StringBuilder and StringBuffer Very similar , There are even compatible ones API, however ,StringBuilder Not thread safe , This is and StringBuffer Main differences .StringBuilder The hierarchy of is as follows :

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

StringBuilder and StringBuffer equally , The main operations are append and insert etc. .

2,StringBuilder principle

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


3, common method

StringBuilder Common methods and StringBuffer It's the same . Listed below :