Foreword: Before we learn the topic String, let us recall whether there is a String type in the C language we learned before. The answer is No. String types are introduced in both C++ and java, which makes it easier for us to process strings on a daily basis.
Previous articles:
[java pieces] package, inheritance, combination
Polymorphism, Abstract class, interface
Is the book management system your final big job?
Say nothing more, do it!!!
1. Understanding String classes
Let's see what the String class is first.
While we are learning java grammar, it is impossible to remember all of the Java grammar very well, so we provide a dedicated reference to the API documentation on Java learning.
1.String type, under the java.lang package, when we use String type, we do not need to import the package manually, the system will import the package itself.
2. The String type is modified by final to indicate that the type cannot be changed, that the class cannot be inherited, and that the String class is a sealed class.
3.String type inherits Object type
4.String type implements Comparator interface (described in previous article), CharSxequence interface, Serializable interface.
When we want to learn a type, we first need to know how it is constructed so that we can learn more about it later.
I've gone, how come there's so much? When will this learn?
In fact, we commonly use two construction methods, the above construction methods we know.
1.String str = "hello world";
2.String str1 = new String("hello world");
Create String
There are two general ways we create strings:
Direct assignment, String str = "hello world";
Another is to use the construction method: String str = new String("abc"); The string in parentheses, which is stored in the value array of the new outgoing object.
String Constant Pool
The string constant pool is implemented using a hash table, so the same string, String type, is not allowed in the constant pool. In shared mode, if the two variables point to the same string, only one string will be reserved in the string constant pool so that both variables point to the string at the same time.
Actually, there is no division of this area in the jvm.
To analyze the code:
public static void main(String[] args) { String str = "123"; String str1 = "123"; System.out.println(str == str1); }
This should be a good judgement, but did you follow this line of thought?
Look at the memory map:
They compare whether the two references are equal. The string contents of str and str1 are hello, so only one copy of "hello" can be stored in the string constant pool. String types have a shared mode, so both references point to a single memory space at the same time.
Storage of string in heap under construction method
String str = new String(abc);
str as a reference refers to an object that has an array of value s pointing to the string that was added.
Disadvantages of assignment using construction methods:
Two blocks of memory must be opened up in the heap, and one will become garbage.
The same string may be stored multiple times, wasting space.
Briefly describe the difference between two assignments of String type:
The first is direct assignment: a block of memory is opened up in the heap, and the incoming string is automatically saved in the string constant pool.
Second: Assignment using a construction method opens up two blocks of memory in the heap, and incoming strings do not go into the pool; they must go into the pool manually through the intern() method.
Case Study:
Please read the following code and answer true or false
Case 1:
public static void main1(String[] args) { String str1 = "hello world"; String str2 = new String("hello world"); System.out.println(str1 == str2);//false }
Let's start by answering the questions. Here's a detailed analysis
At a glance, what's rare about this? It's not a comparison. These two strings are not equal, they are not true.
Ha-ha, come on, the answer is false. In fact, they compare two string references, which is equivalent to the pointer we learned in C language stage. There was no pointer in java at that time, and this reference was not as flexible as the pointer in C/C++.
str1 as a reference opens up space in the stack frame, and the value given to str is stored on the stack
As a reference, str2 references an object of type String, which opens up space on the stack and stores the object on the stack.
Look at the picture and talk:
Analysis:
- STR1 is assigned a direct value, passing the string "hello world" to str1, and in the heap, any constants caused by double quotation marks are stored in the string constant pool.
- str2 is a reference, he points to an object, there is a value array inside the object, this array refers to the value stored inside the object, that is, the value array inside the object refers to the string "hello world", because the string is to be stored in the string constant pool, which before had "hello world" This string and mentioned earlier that the string constant pool is made up of a hash table, so this object points to a string constant already in the string constant pool.
Case 2:
Look at the next code:
public static void main(String[] args) { String str1 = "hello world"; String str2 = "hello " + "world"; System.out.println(str1 == str2); }
The answer is true
Why?
Because string constants are connected at compile time, that is, "hello" + world"becomes"hello world", and because when str2 is executed, the string"hello world"already exists in the character constant pool in the heap, when str2 points to this connected string that will be stored in the pool, First check to see if the pool already has a string to store, and if so, str2 points to the existing string.
If you don't believe it, we'll decompile it to see if stitching was done at the time of compilation.
Look at the picture and talk:
Constants are already computed during compilation.
Case 3:
Please read the code:
public static void main(String[] args) { String str1 = "hello world"; String str2 = "hello " + new String("world"); System.out.println(str1 == str2); }
The answer is false
Why?
Because when str2 is executed, this code references a String object that points to a string "world" stored in a pool of string constants and the string "world" referenced by the String object is spliced with "hello" in the pool to form a new object, which involves the StringBuffer/StringBuilder knowledge point. We'll cover that later in the article, and this str3 points to this new object, which naturally does not have the same address as the "hello world" that str1 points to.
Look at the picture and talk:
Case 4:
Read the following code:
public static void main(String[] args) { String str1 = "hello world"; String str2 = "hello "; String str3 = str2 + "world"; System.out.println(str1 == str3); }
The answer is: false
Why?
Because str2 becomes a variable when we execute the str3 code, let's recall what the concept of a variable is, that is, a variable is compiled without knowing what's inside it, and only when it's running does it know what's inside. During the string splicing process, a new object will be formed, str3 will point to this object, str1 will point to a string, obviously they will not point to the same address, so it is false.
Look at the picture and talk:
Case 5:
Please read the code:
public static void main(String[] args) { String str1 = "hello world"; String str2 = new String("hello ") + new String("world"); System.out.println(str1 == str2); }
When you do this, it is easy to tell that the answer must be false, because str1 and str2 do not point to the same address.
Look at the picture and talk:
Case 6:
Please read the code:
public static void main(String[] args) { String str1 = "hello world"; String str2 = new String("hello world"); str2.intern(); System.out.println(str1 == str2); }
The answer is: false
Here you have to introduce the intern() method, which manually fills a string into the pool of string constants.
We know that STR2 is a reference, it refers to a String object, it has a value array inside it, this value array refers to a string, this string "hello world" already exists in the string constant pool, even if it is manually filled in with this existing string, A pool of string constants is also implemented by a hash table in which duplicate values are not allowed. So str2.intern(), this piece of code, where there is no code, has the same result, which means it has done nothing.
Look at the picture and talk:
It has the same memory diagrams as the cases, so we won't go into much detail here.
Case 7:
Please read the code:
public static void main(String[] args) { String str1 = new String("1") + new String("1"); str1.intern(); String str2 = "11"; System.out.println(str1 == str2); }
The answer is:true
Why?
Analysis:
Both objects refer to a string of "1". When two strings are joined together to form a new string "11", they are manually added to the string constant pool. When the code executes to str2, the string it refers to is "11", which already exists in the pool, so there is no need to add it. In this case, STR2 refers to the string "11", assuming that the string "11" is now joined. The address is 0x123, so the object that points to it is also 0x123, so str1 and STR2 have the same address
Look at the picture and talk:
Case 8:
Please read the code:
public static void main(String[] args) { String str1 = new String("1") + new String("1"); String str2 = "11"; str1.intern(); System.out.println(str1 == str2); }
The answer is: false
Why?
Because the string "11" is joined by two objects, and then STR2 points to the string "11", and now the string "11" in the string constant pool refers to str2, you can manually add the joined string to the string constant pool, but you already have this character, so you cannot add it manually.
str1 points to a string, str2 points to a referenced object, their references are different, so they are false.
Case 9:
Take a look at the code:
public static void func(String str) { str = "bit"; } public static void main(String[] args) { String str = "gaobo"; func(str); System.out.println(str); }
The answer is: gaobo
Why?
Because the STR in the main method here points to a string stored in the pool of string constants in the heap, and what we pass to the func method is an str reference, which originally points to the same block address as the str reference in the main method, but in the func method, the str reference points to a new address (that is, the address of "bit" in the string constant pool of the heap area), so the two are not pointing to a single address, so they are not the same. From the code above, we can see that the final printed result is "gaobo".
Look at the picture and talk:
Case 10:
Take a look at the code:
public static void main(String[] args) { String str1 = "Hello"; String str2 = str1; str1 = "world"; System.out.println(str1 == str2); }
The answer is: false
Why?
Consistent with the previous question, str1 is a reference to "Hello" in the pool of string constants in the heap. str2 refers to the object that str1 refers to (the string "Hello"), so the first two references point to the same address, but str1 refers to a new address (the address space where "world" is located) So when you compare two references, they are definitely not equal.
Look at the picture and talk:
Understand the difference between = and equal s correctly
- Double equals compares whether two string references are equal, that is, whether the addresses they point to are equal
- equal compares whether the contents of two strings are identical.
Use of the equal method:
public static void main(String[] args) { String str1 = "hello world"; String str2 = "hello world"; System.out.println(str1.equals(str2)); }
Both strings have the same content, returning true, or returning false. But if one is empty, that's the only way to write it.
public static void main(String[] args) { String str1 = null; String str2 = "hello world"; System.out.println(str2.equals(str1)); //System.out.println("hello world".equal(str1))); best written like this }
Because if str1 is compared before the equal() method, a null pointer exception occurs
Understanding string immutability:
We also saw the source code for String.java before the article, knowing that the String class (decorated with final) is a sealed class that cannot be inherited, and that the object referenced by the String cannot be modified.
A string is an immutable object whose contents cannot be modified
Let's look at the following code:
String str = "hello" ; str = str + " world" ; str += "!!!" ; System.out.println(str); // results of enforcement hello world!!!
Apparently, you just add the string you want to add directly after the original string, but that's not the case.
Please take a closer look at his memory map:
In the string constant pool, each stitching will result in a new object. When the code executes to str = str + "world", STR is equivalent to a variable. Variable and string stitching will need to reclaim a new memory space in the heap, and the value array in this memory space will point to the stitched string "hello world", which is stitched together. "!!!" "The same is true when opening up a new memory space in which the value array will point to the stitched"hello world!!!"Where the str reference points to the stitched string.
You can think about whether these two will waste space if you keep on stitching. Just to get the last stitched string, then in order to stitch this string, do you have a lot of strings behind the stitched string to create more space for stitching, which will reduce the free space in the heap area? TringBuffer/StringBuilder does not need to be spliced once to create space, but splices directly at the end of the original string.
This also implies that the string is immutable and cannot be modified on the same string.
So what if we really want to modify the string?
Take a look at the code in detail:
String str = "Hello"; str = "h" + str.substring(1); System.out.println(str); // results of enforcement hello
The substring() method, which intercepts strings, intercepts the subscript according to which elements are used in the string.
In the above code, all the strings ("ello") after "h ello" are intercepted, and then stitched with the string "h". But this is not directly stitched after the string "h". Or you need to reclaim a space in the heap where the value array points to the stitched "h ello" string.
So, if we really want to make changes in the original string, then we have to briefly introduce reflection (here is a brief introduction)
Reflection is an important feature of object-oriented programming and is called "introspection" in some languages.
The nature of reflection: Reflection is the process of getting specific information (member properties, member methods) to modify an object while the program is running, which is equivalent to letting the object know itself better.
So now we'll use the reflection feature to modify the string.
We can see from the source code of the String class that the field referenced by the String is not modifiable and that the field is a private property in the class.
String str = "hello world"; // Get byte code object Class c = String.class; //Gets the value field in the String class Field field = c.getDeclaredField("value"); //Modify string permissions to true field.setAccessible(true); //Get val in str char[] vals = (char[]) field.get(str); //Modify strings vals[0] = 'H'; System.out.println(vals);
Run result: Hello world
And it is modified on the original string, no new space has been reclaimed.
2. Characters, bytes, strings
Characters and Strings
Characters and Strings
Inside the string is an array of chars [] the same as the string, which can be converted to and from characters.
No | Method Name | type | describe |
---|---|---|---|
1 | public String(char[]chars) | Construction method | Convert Characters to Strings |
2 | public String(char[] chars,int offest,int count) | Construction method | Offest denotes offset position, count denotes offset, converting a character array from an offset of count characters after offest to a string |
3 | public charAt(int index) | General method | index stands for subscript, and the character corresponding to the subscript is found in the string |
4 | public toCharArray(String str) | General method | Convert a string to an array of characters |
Method 1:
Convert Characters to Strings
public static void main(String[] args) { char[] array = {'a', 'b', 'c', 'd'}; String str = new String(array); System.out.println(str); } //Run result: abcd
Method 2:
From the offset point, convert the offset characters into strings
public static void main(String[] args) { char[] chars = {'a','b','c','d','e','f'}; String str = new String(chars,2,3); System.out.println(str); } //Run result: cd
Method 3:
Find a character in the string with the subscript i
public static void main(String[] args) { String str = "abcdefg"; char ch = str.charAt(5); System.out.println(ch); } //Found character with subscript 5 //The result is:f
Method 4:
Converts a string to an array of characters
public static void main(String[] args) { String str = "abcdef"; char []chars = str.toCharArray(); System.out.println(Arrays.toString(chars)); } //Running result: [a,b,c,d,e,f]
Method short training:
Determine if a string is full of numbers?
The known string is "158946a9";
public static boolean isNUmber(String str){ if(str.length() == 0){ //Determine if the string passed is zero length return false; } if(str == null){ //Determine if the string passed in is null return false; } for(int i = 0;i<str.length();i++){ if(str.charAt(i)>'9' || str.charAt(i) < '0'){ return false; } } return true; } public static void main(String[] args) { String str = "158946a9"; System.out.println(isNUmber(str)); } //Run result false
Bytes and Strings:
Bytes are commonly used for data transfer and encoding conversions, and String can also convert to and from bytes
NO | Method Name | type | describe |
---|---|---|---|
1 | public String(Byte[] byte) | Construction method | Convert an array of bytes to a string |
2 | pubic String(Byte[] byte,int offest,int count) | Construction method | Convert from offset point of offest of byte array to count byte elements to string |
3 | public byte[] getBytes(String str) | General method | Converts all characters in a string to a byte array |
4 | public byte[] getBytes(String CharsetName)trows unspportedEncodingException | General method | Coding Processing |
Method 1:
Convert an array of bytes to a string
public static void main(String[] args) { byte []bytes = {97,98,99,100}; String str = new String(bytes); System.out.println(str); } //Run result: abcd
Method 2:
Convert from offset point of offest of byte array to count byte elements to string
public static void main(String[] args) { byte[]bytes = {97,98,99,100,101,102}; String str = new String(bytes,1,3); System.out.println(str); } //Run result: bcd
Method 3:
Converts all characters in a string to a byte array
public static void main(String[] args) { String str = "abcdef"; byte[]bytes = str.getBytes(); System.out.println(Arrays.toString(bytes)); } //Running result: [977,98,99,100,101,102]
Method 4:
Coding Processing
1.UTF-8 encoding:
public static void main(String[] args) java.io.UnsupportedEncodingException{ String str = "abcde high"; byte[]bytes = str.getBytes("UTF-8"); System.out.println(Arrays.toString(bytes)); } //Running result: [97, 98, 99, 100, 101, -23, -85, -104] //Here is UTF-8 encoding, we don't know what he compiled the Chinese characters into
2.GBK encoding:
public static void main(String[] args)throws java.io.UnsupportedEncodingException { String str = "abcde high"; byte[]bytes = str.getBytes("GBK"); System.out.println(Arrays.toString(bytes)); } //Running result: [97, 98, 99, 100, 101, -72, -33]
So after UTF-8 encoding and GBK encoding, the result of the character array is different.
Analyzing when character arrays are used and in which cases byte arrays are used
- Byte[] String is treated as a byte by byte, which is suitable for use in scenarios such as network transport, data storage, etc. It is more suitable for binary data operations.
- char[] Yes, String is treated one character at a time, which is more suitable for text data, especially when Chinese is included
3. Common string operations:
String comparison:
Previously, we introduced the string comparison function equal(), which distinguishes between uppercase and lowercase characters. Here, we will discuss how to compare strings.
NO | Method introduction | type | Effect |
---|---|---|---|
1 | public boolean equal(String str) | General method | Compare strings (case sensitive) |
2 | public boolean equalIgnoreCase(String str) | General method | Compare strings to be equal (case insensitive) |
3 | public int compareTo(String str) | General method | Comparing string sizes Returns a positive number if one string is larger than the other, or a negative number if it is equal, returns 0 |
Method 1:
Compare strings (case sensitive)
public static void main(String[] args) { String str = "hello"; String str1 = "Hello"; System.out.println(str.equals(str1)); } //Run result: false
Method 2:
Compare strings to be equal (case insensitive)
public static void main(String[] args) { String str = "hello"; String str1 = "Hello"; System.out.println(str.equalsIgnoreCase(str1)); } //Return true
Method 3:
Comparing string sizes Returns a positive number if one string is larger than the other, or a negative number if it is equal, returns 0
public static void main12(String[] args) { String str = "hello"; String str1 = "Hello"; System.out.println(str.compareTo(str1)); } //Run Result 32
public static void main(String[] args) { String str = "abcdef"; String str1 = "abc"; System.out.println(str.compareTo(str1)); } //Run Result 3
If the length of the string is equal, the compareTo() method returns the difference between the ASI codes of the characters, and if the length of the string is not equal, it returns the difference between their lengths.
So let's look at the source code for the compareTo() method
String splitting:
You can split a string by a specific character. Become several substrings.
No | Method Name | type | Effect |
---|---|---|---|
1 | public String split(String regex) | ordinary | Split String |
2 | public String split(String regex,int limit) | ordinary | Split string, limit represents the limit of the number of split groups |
Method 1:
Split String
public static void main(String[] args) { String str = "a b c d e f"; String str1 = " "; String[]strings = str.split(str1); for (String s:strings) { System.out.println(s); } } //Run Results //a //b //c //d //e //f
Method 2:
Split string, limit represents the limit of the number of split groups
public static void main(String[] args) { String str = "a b c d e f"; String str1 = " "; String[]strings = str.split(2); for (String s:strings) { System.out.println(s); } } //Run result: //a //b c d e f
So when we want to split an IP address, can it still be the same as above?
That's definitely not the case!!!
public static void main(String[] args) { String str = "19.15.5.4"; String []strings = str.split("\\.");//If no escape character is added, the printed result is incorrect for (String s:strings) { System.out.println(s); } } //The results are: //19 //15 //5 //4
Matters needing attention:
When the delimiter is **'+', *', |'always precede with a transfer character'/';**
If it is "", add "//" before it;
Use'|'to separate multiple separators.
Multiple separators in string
public static void main(String[] args) { String str = "19&18%14#13"; String []strings = str.split("&|%|#"); for (String s:strings) { System.out.println(s); } }
Implement multicomponent splitting:
public static void main(String[] args) { String str = "18#15#16&11&100"; String []strings = str.split("#"); for(String s1 : strings){ String []s = s1.split("&"); for(String ss: s){ System.out.println(ss); } } } //Run result: //18 //15 //16 //11 //100
String substitution:
Replace a string with a specific new string.
No | Method Name | type | Effect |
---|---|---|---|
1 | public String replace(String regex,String replacement) | ordinary | Replace String |
2 | public String replaceAll( String regex,String replacement) | ordinary | Replace a specific string used in a string |
3 | public String replaceFirst(String regex,String replacement) | ordinary | Replace first content |
Method 1:
Replace String
public static void main(String[] args) { String str = "a b c d "; String str1 = str.replace(" ","1"); System.out.println(str1); } //Run result a1b1c1d1
Method 2:
public static void main(String[] args) { String str = "a b c d "; String str1 = str.replaceAll(" ","1"); System.out.println(str1); } //Method 1 and method 2 perform the same result
Method 3:
Replace first content
public static void main(String[] args) { String str = "a b c d e"; String str1 = str.replaceFirst(" ","1"); System.out.println(str1); } //Run result: a1b c d e
String lookup:
Determines whether the specified content exists from a complete string.
No | Method Name | type | Effect |
---|---|---|---|
1 | public boolean contains( CharSequence str) | General method | Find another string in one string |
2 | public int indexOf(String str) | General method | Finds a string in a string, returns its subscript if found, and returns -1 if not found |
3 | public int indexOf(String str,int fromIndex) | General method | Search for string from specified location, return index found, Return-1 not found |
4 | public int lastIndexOf(String str) | General method | Find the specified string backward and forward |
5 | public int lastIndexOf(String str,int formIndex) | General method | Finds a string from the specified location, back to front |
6 | public boolean startsWith(String prefix) | General method | See if the beginning of the string has been specified |
7 | public boolean startWith(String prefix,int formIndex) | General method | Determines whether a specific string has started at the specified position |
8 | public boolean endsWith(String suffix) | General method | See if it ends with a specific string |
Method 1:
Find another string in one string
public static void main(String[] args) { String str = "abcdef"; String str1 = "ab"; System.out.println(str.contains(str1)); } //Run result:true
Method 2:
Finds a string in a string, returns its subscript if found, and returns -1 if not found
public static void main(String[] args) { String str = "ancdef"; String srr1 = "cd"; System.out.println(str.indexOf(srr1)); } //Run result: 2
Method 3:
Search for string from specified location, return index found, Return-1 not found
public static void main(String[] args) { String str = "decfgh"; String str1 = "de"; System.out.println(str.indexOf(str1,2)); } //Run result: -1
Method 4:
Find the specified string backward and forward
public static void main(String[] args) { String str = "abndefg"; String str1 = "nd"; System.out.println(str.lastIndexOf(str1)); } //Run result: 2
Method 5:
Finds a string from the specified location, back to front
public static void main(String[] args) { String str = "ababrag"; String str1 = "ab"; System.out.println(str.lastIndexOf(str1,2)); } //Run result: 2
Method 6:
See if the beginning of the string has been specified
public static void main(String[] args) { String str = "abcdefgt"; String str1 = "abc"; System.out.println(str.startsWith(str1)); } //Run result:true
Method 7:
Determines whether a specific string has started at the specified position
public static void main(String[] args) { String str = "abcdef"; String str1 = "a"; System.out.println(str.startsWith(str1,1)); } //Run result: false
Method 8:
See if it ends with a specific string
public static void main(String[] args) { String str = "abcde"; String str1 = "de"; System.out.println(str.endsWith(str1)); } //Run result:true
String interception:
Intercepts part of a string.
No | Method Name | type | Effect |
---|---|---|---|
1 | public String subString(int index) | ordinary | Intercept string from index |
2 | public String subString(int index,int count) | ordinary | Intercept the string between index and count, noting the open interval before and after closing |
Method 1:
Intercept string from index
public static void main(String[] args) { String str = "abcdef"; String str1 = str.substring(2); System.out.println(str1); } //Run result cdef
Method 2:
Intercept the string between index and count
public static void main(String[] args) { String str = "abcdef"; String str1 = str.substring(2,5); System.out.println(str1); } //Run result: cde note is [2,5]
Other methods of operation:
No | Method Name | type | Effect |
---|---|---|---|
1 | public String trim() | ordinary | String left and right spaces removed, middle spaces unchanged |
2 | public String toUpperCase() | ordinary | Change all characters in the string to uppercase |
3 | public String toLowerCase() | ordinary | Change all characters in the string to lowercase |
4 | public native iterm() | ordinary | Pool Strings |
5 | public String concat(String str) | ordinary | String connection, similar to'+' |
6 | public int length() | ordinary | Calculate the length of a string |
7 | public boolean IsEmpty() | ordinary | Determine if the current string is empty |
**This method blogger did not introduce one by one, we completed it on idea by ourselves. The specific functions of each method are clearly described. ** This is also common in the process of writing code later on.
4. Differences between String, StringBuilder, and StringBuffer:
We know that String is used to describe strings, and String-type variables point to content that cannot be modified. Although this makes the program safe, it brings us a lot of inconvenience when we use strings to solve problems in general. Two StringBuilder and StringBuffer keywords have been derived. These two keywords modify what can be changed by strings, and StringBuilder and StringBuffer have essentially the same methods.
We know that there are two ways a String type defines a variable, one is to assign it directly (String str = "abc") and the other is to newan object whose array of value s points to the string to be added (String str = new String("abc"); But there is only one assignment in StringBuffer and StringBuilder, which is construction.
StringBuffer sb = new StringBuffer("abc");
We know that concatenating strings in String results in a new object on the heap that has a value array pointing to a stitched string. However, when modified by StringBuffer and StringBuilder, if you want to stitch strings, you add them directly at the end of a string. No new objects will be created, so that no more space will be used to apply for objects, which will consume space.
Appnd() method when splicing strings in StringBuffer and StringBuider
Here, using StringBuffer, why can a string be modified by it?
Let's take care of its source:
We can see that in the source code corresponding to the append() method, this. is the current object, so we don't have to repeat the request space on it.
Take a look at the code
public static void main(String[] args) { String str = new String("abc"); for(int i = 0;i<10;i++){ str += i; } System.out.println(str); }
See the source code:
Although StringBuilder is optimized here, we need a new object every time we cycle, so we should never write code like this in the future.
Conversion between String and StringBuilder,StringBuffer
Stringhe StringBuilder,Stringbuffer can not be directly converted between,
String becomes StringBuffer: Use StringBuffer's construction method or append() method
StringBuffer becomes String: the toString() method is called.
public static void main(String[] args) { //String becomes StringBuffer String str = "hello"; StringBuffer stringBuffer = new StringBuffer(str); //StringBuffer stringBuffer = new StringBuffer(); //String str1 = stringBuffer.append(str); System.out.println(stringBuffer); System.out.println(str1); //Run result is hello }
public static void main(String[] args) { //StringBuffer becomes String StringBuffer stringBuffer = new StringBuffer("abc"); String str = stringBuffer.toString(); System.out.println(str); }
In addition to the append() method, StringBuffer also has methods that String does not have, such as string flip`.
public static void main(String[] args) { StringBuffer stringBuffer = new StringBuffer(); StringBuffer str = stringBuffer.append("abcdef"); StringBuffer str1 = str.reverse(); System.out.println(str1); //Run result is fedcba }
Provision string deletion
public static void main(String[] args) { StringBuffer stringBuffer = new StringBuffer(); StringBuffer str = stringBuffer.append("abcdef"); //Delete specified string StringBuffer str1 = str.delete(2,4); System.out.println(str1); } //Run result aef
Insert a character into a string
public static void main(String[] args) { StringBuffer stringBuffer = new StringBuffer(); StringBuffer str = stringBuffer.append("abcd"); StringBuffer str1 = str.insert(2,"dd"); System.out.println(str1); } //Run result is abddcd
Near the end, let's finish today's blog with a classic interview question!!
Interview Question: Differences between String,StringBuffer,StringBuilder
String-modified strings cannot be modified, strings modified by StringBuffer and StringBuilder can be modified.
A comparison between StringBuffer and StringBuilder: StringBuffer uses synchronization and is a thread-safe operation; StringBuilder does not use synchronization and is a thread-insecure operation
StringBuffer and StringBuilder use much of the same methods.
Let's take a look at the source code for StringBuffer and StringBuilder, respectively!!
Source code for StringBuffer:
Source code for StringBuilder:
As we can see from the source comparison between StringBuffer and StringBuilder, the method of StringBuffer has been modified by synchronized
So we know what synchronized does, and that's how it keeps threads safe.
StringBuffer is typically used for multithreading, and StringBuilder is typically used for single threading.
Then some children's shoes ask what is thread safety and what is thread insecurity?
Bloggers here give an embarrassing but helpful example.
If you go to the toilet, there is a group of people waiting for you outside the toilet door. Everyone needs to go to the toilet. If you don't have a lock to lock the door, people crowd into the toilet and you are going to the toilet, it's embarrassing. And the lock is synchronized.