In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the use of String class in Java". In daily operation, I believe that many people have doubts about the use of String class in Java. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what is the use of String class in Java?" Next, please follow the editor to study!
First, create a string
There are three ways to create a string:
/ / Mode 1 String str = "Hello Bit"; / / Mode 2 string str2 = new String ("Hello Bit"); / / Mode 3 char [] array = {'a', 'baked,' c'}; String str3 = new String (array)
We are already very familiar with the first and second methods of creating a string, so as to why the third kind can pass in a character array into a string, we can press and hold the ctrl key and click into the String of the incoming character array to see its original code, we can find that the method used at this time is to copy the array and change all the characters of the character array into a string form.
Second, character, byte and string conversion 1. Conversion between character and string
Because a string is equivalent to a collection of characters, to convert a character to a string, call the constructor of String and pass in an array of characters. For example:
Char [] val = {'axiaqiaojie]; String str = new String (val); System.out.println (str)
Of course, we can also choose which subscript to convert the character array from which subscript begins to which subscript ends into a string.
For example:
Char [] val = {'axie'}; String str1 = new String (val,0,3); System.out.println (str1); / / print result is abcSystem.out.println ("="); String str2 = new String (val,1,3); System.out.println (str2); / / print result is bcd
Because a string is a collection of characters, a string can be converted to a character or an array of characters. Parentheses such as 0 and 1 are offsets, which start at 0, so take 3 characters back from the position where the offset is 0 to form a string.
If the string is to be converted to a single character, the code is as follows:
String str = "abc"; System.out.println (str.charAt (1)); / / print the result as b
If the string is to be converted to a character array, the code is as follows:
Char [] val = str.toCharArray (); System.out.println (Arrays.toString (val)); / / print result: [a, b, c] 2. Conversion between bytes and strings
Converting bytes to strings in Java requires converting an array of bytes to strings.
Convert a byte array to a string:
Byte [] bytes = {97 new String (bytes,0,3); System.out.println (str1); / / print result is abcSystem.out.println ("="); String str2 = new String (bytes,1,3); System.out.println (str2); / / print result is bcd
Convert a string to a byte array:
String str1 = "abc"; byte [] bytes1 = str1.getBytes (); System.out.println (Arrays.toString (bytes1)); / / the printed result is: [97,98,99] III. Comparison of strings
Many beginners will think that "=" compares with equals in the same way. In fact, there is a big difference.
When comparing two strings with "=", you compare references to variables. String's equals method compares the contents of two strings. At this point, however, there is another question: why is there a reference that defines a string constant? This involves the string constant pool.
1. String constant pool
For the concept of "pool", we may still be relatively strange. For example, data connection pool, thread pool, and so on. So what are these pools for? Is used to improve storage efficiency. As the name implies, the string constant pool is used to store string constants. The string constant pool specifies that as long as there is a string constant, the same string will no longer be stored. Starting with JDK1.8, the string constant pool is in the heap. It is essentially a hash table (StringTable) is an array. The storage string constant is stored according to a mapping relationship that requires a hash function to be designed. Because the string constant pool is about JVM, we need to look at its original code to really understand how the string constant pool works. If we don't delve into the principle here, it won't affect us to judge whether the references are the same.
When a string constant is stored in the string constant pool, a node is generated at a location calculated according to the hash function. The node is composed of the hash value, the address of the String node, and the address of the next node at the location of the array (which can only be truly understood in the source code of the JVM). Each String node is made up of a character array value and a hash value of hash (default is 0) (shown in the following figure). When you click String to see its original code, you will find these two variables. At this point, it is observed that the value array is modified by final, which means that the characters in the array cannot be changed, which is why the string is a constant, and the string will be converted to character form and stored in the character array.
Let's start with a relatively simple example to understand the memory layout of a string constant pool.
The code is as follows:
Code 1:
String str1= "hello"; String str2 = "hello"; System.out.println (str1==str2); / / print the result as true
The memory layout is as follows:
Code 2:
String str1= "hello"; String str2 = new String ("hello"); System.out.println (str1==str2); / / print the result as false
Enter the pool manually:
We know from the figure above that the run result in Code 2 is false, because str2 points to the String object generated by new String, not the address of the String object where "hello" is stored. What would be the result if written as the following code?
String str1= "hello"; String str2 = new String ("hello"). Intern (); System.out.println (str1==str2); / / the result is true
Why did the final result be true? At this point, the intern method in the String class, called manual pooling, is called, which points the str2 to a String object that no longer comes out of new, but to a String object that already has an array of "hello" characters stored in the string constant pool.
Code 3:
String str1= "hello"; String str2 = "he" + "llo"; System.out.println (str1==str2); / / print the result as true
This code is about string concatenation. In fact, "he" and "llo" have been compiled to "hello" at compile time. If you want to see what string str2 is at compile time, click on the Build option at this time, and click on the Build Project option to compile (figure 1). You can in the path of this class file (containing .class file) (figure 2 + figure 3), hold down the shift key and right-click on the powershell window, enter the decompilation instruction javap-c class name, you can see whether the compile-time str2 is a spliced hello.
Figure 1:
Figure 2: right-click on the window of this class
Figure 3: return to the previous folder, click out- > prodection- > the folder name where the bytecode file is located-> hold down shift and click the right mouse button to click into the powershell window-> enter the javap-c class name
Code 4:
String str1= "11"; String str2 = new String ("1") + new String ("1"); System.out.println (str1==str2); / / the result is false
String concatenation produces a StringBuffer type, and calling the toString method through StringBuffer is also transformed into a String class, where the string "11" is stored in value, but not in the string constant pool.
Through decompilation we see that the splicing does produce StringBuffer, and the StringBuffer calls the toString method to produce an object store of the String class "11". It can be fully understood by figures 1 and 2.
Figure 1:
Figure 2:
Figure 3:
two。 String content comparison
For string comparison, we cannot directly use "= =", but there are three ways to compare strings in different ways.
Compare string contents: call the equals method of the String class directly and compare the strings in parentheses.
Compare string contents (regardless of letter case): call the equalsIgnoreCase method of the String class.
String str1 = "hello"; String str2 = "Hello"; System.out.println (str1.equals (str2)); / / false System.out.println (str1.equalsIgnoreCase (str2)); / / true
Compare the size of the string: call the compareTo method in the String class. Originally, there is no compareTo method in the String class, but the String class implements the Comparable interface and overrides the compareTo method.
It is compared character by character. If str1 is greater than str2, the value of the character str1 minus str2 is returned. For example:
Code 1:
String str1 = "abc"; String str2 = "bcd"; System.out.println (str1.compareTo (str2)); / / the running result is-1
Because the ASCII code value of b is 1 greater than the ASCII code value of a,-1 is returned directly. (if the characters are different, return their ASCII code difference)
Code 2:
String str1 = "bcdef"; String str2 = "bcd"; System.out.println (str1.compareTo (str2)); / / the running result is 2
Because the character value is the same as str1 before the end of the str2 comparison. So the end result is the length of str1 minus the length of str2.
The following is the implementation of the compareTo method of the String class.
IV. String search
1. Determine whether a substring exists in the main string: call the contains method of the String class and the return value is boolean.
String str = "abbabcacc"; boolean flg = str.contains ("abc"); System.out.println (flg); / / print the result as true
two。 Looks for a substring from scratch and returns the index position at the beginning of the first substring, or-1 if not. You can also pass in an index that represents where to start the search, and call the indexOf method in the String class.
String str = "abbabcacc"; int index = str.indexOf ("abc"); System.out.println (index); / / print result is 3
3. Start looking at the end to see if there are any incoming substrings in the main string. If so, the index value will be returned. If not,-1 will be returned. Call the lastIndexOf of the String class, and you can also pass in the index representation from which index value is found from the end to the end. Call the lastIndexOf of the String class
Code 1:
String str = "abbabcacc"; int index = str.lastIndexOf ("ac"); System.out.println (index); / / print result is 6
When the substring we are looking for happens to be "cut off", it still takes the following characters and returns the index value at the beginning of the substring, but the index value of the subsequent characters cannot be obtained.
Code 2:
String str = "abbabcacc"; int index = str.lastIndexOf ("ac", 6); System.out.println (index); / / print result is 6
4. Call the startsWith method in the String class to determine whether a string begins with a specified substring. You can also pass in an index value indicating whether to start with a specified substring from the specified position.
String str = "abbabcacc"; boolean flg = str.startsWith ("abb"); System.out.println (flg); / / print result is trueString str = "abbabcacc"; boolean flg = str.startsWith ("abb", 3); System.out.println (flg); / / print result is false
5. Determines whether a string ends with a specified substring. Call the endsWith method in the String class.
String str = "abbabcacc"; boolean flg = str.endsWith ("acc"); System.out.println (flg); / / print the result as true, string substitution
1. Replaces all the specified contents in the string. Call the repalceAll method in the String class.
String str = "helloworld"; System.out.println (str.replaceAll ("l", "_")); / / print the result as he__owor_d
You can also choose to replace the first content in the string. Call the repalceFirst method in the String class.
System.out.println (str.replaceFirst ("l", "_")); / / print the result as he_loworld
Because the string is an immutable object, substitution does not modify the current string, but produces a new string.
VI. String splitting
To specify that a string can be divided into several groups on the basis of the main string is equal to several String-like arrays. So you can iterate through the contents of the split array through the foreach loop. Call the split method of the String class.
String str = "hello world hello bit"; String [] result = str.split (""); / / split for (String s: result) {System.out.println (s) by space;} / / print the result as
Hello
World
Hello
Bit
The split method can also pass in a limit parameter, which means that the split can be divided into at most several arrays. If the number of arrays after split is less than this limit value, it will be split according to the number of arrays that were originally split, otherwise the number of arrays cannot exceed the value.
String str = "hello world hello bit"; String [] result = str.split ("", 2); for (String s: result) {System.out.println (s);} / / print the result as
Hello
World hello bit
Of course, the splitting of a string can be nested, that is, it can be split into two parts, and then split according to another string.
String str = "name=zhangsan&age=18"; String [] strings = str.split ("&"); for (String s:strings) {String [] ss = s.split ("="); for (String s1:ss) {System.out.println (S1);}} / / print the result as
Name
Zhangsan
Age
eighteen
There are several special cases for the splitting of a string. When you encounter an escaped character that needs to be split, passing in the specified string requires passing two more slashes. For example:
String str = "192.168.1.1"; String [] strings = str.split ("\\."); for (String s:strings) {System.out.println (s);} / / the printed result is
one hundred and ninety two
one hundred and sixty eight
one
one
Therefore, it is important to note that the characters "|", "*" and "+" have to be escaped, preceded by "\".
The splitting of a string can also be split based on multiple specified strings, separated by'|'.
String str = "Java30 12&21#hello"; String [] strings = str.split ("| & | #"); for (String s:strings) {System.out.println (s);} / / the printed result is
Java30
twelve
twenty-one
Hello
VII. String interception
For the interception of a string, pass in an index value that represents which index to start the interception from. Passing in two index values represents the intercepted range. Call the substring method in the String class. For example:
String str = "helloworld"; System.out.println (str.substring (5)); System.out.println (str.substring (0,5)); / / print the result as
World
Hello
Note:
Index starts at 0
Pay attention to the writing of the opening interval before and after closing. Substring (0,5) indicates a character containing subscript 0, not subscript 5.
For the above string manipulation method, we can look at the original code to better understand how the method operates.
8. Other common methods in the string class
The trim method of the 1.String class. This method is used to remove the spaces on the left and right sides of the string, and the spaces in the middle of the string will not be removed.
Code:
String str = "abc def"; String s = str.trim (); System.out.println (s); / / the printed result is
Abc def
ToUpperCase and toLowerCase methods in the 2.String class. ToUpperCase is used to convert lowercase letters in a string to uppercase letters, rather than unprocessed letters. The toLowerCase method is used to convert uppercase letters in a string to write letters, and non-alphabetic letters are not processed.
String str = "hello%$$%@#$%world ha ha"; System.out.println (str.toUpperCase ()); System.out.println (str.toLowerCase ()); / / print the result as follows:
HELLO%$$%@#$%WORLD. Ha.
Hello%$$%@#$%world. Ha.
The concat method in the 3.String class. This method is used to concatenate a string, which is equivalent to a concatenation in a string, but the concatenated string does not go into the string constant pool. There is no more demonstration here.
The length method in the 4.String class. It is used to find the length of a string. Unlike an array, length in an array is an attribute of an array, while length in String is a method.
Code:
String str = "abcd"; System.out.println (str.length ()); / / print result is 4
The isEmpty method in the 5.String class. Is used to determine whether the string is empty.
Code:
System.out.println ("hello" .isEmpty ()); / / falseSystem.out.println ("" .isEmpty ()); / / trueSystem.out.println (new String () .isEmpty ()); / / truth nine, StringBuffer and StringBuilder
With an understanding of the String string constant pool above, we know that String is constant and immutable. When stitching, Java will optimize the object stitching of the String class to the splicing of StringBuffer during compilation (no new objects will be generated), so there are strings in StringBuffer and StringBuilder in Java, and when they are stitched together, they will not produce new objects, but will be spliced on the basis of the original string. Later we will discuss the difference between StringBuilder and StringBuffer.
There is an append method in StringBuilder that can concatenate strings based on the original. For example, when we have code like this:
String str = "abc"; for (int I = 0; I < 10; iTunes +) {str+=i;} System.out.println (str); / / print the result:
Abc0123456789
A lot of temporary variables are generated in the constant pool, for example, abc0 is generated in the string constant pool, abc01 is generated in the string constant pool, and so on. If we use StringBuilder's append method, it can be written as (the final result of the two methods is the same, except that StringBuilder processing does not produce temporary variables in the string constant pool):
StringBuilder stringBuilder = new StringBuilder ("abc"); for (int I = 0; I < 10; iTunes +) {stringBuilder.append (I);} System.out.println (stringBuilder); / / print the result:
Abc0123456789
The reason why the StringBuilde type can be printed when printing is that the toString method of the parent class is overridden in StringBuilder, which can convert the StringBuilder type to the String type for printing.
The append method can also be used in conjunction with it. The code is as follows:
Public static void main (String [] args) {StringBuffer sb = new StringBuffer (); sb.append ("Hello"). Append ("World"); fun (sb); System.out.println (sb);} / / print the result as
HelloWorld
Therefore:
String becomes StringBuffer: using the constructor of StringBuffer or the append () method.
StringBuffer becomes String: call the toString () method.
The difference between 1.StringBuilder and StringBuffer
The methods in StringBuilder and StringBuffer are roughly the same. The main difference between them is that StringBuilder is mainly used for single thread, while StringBuffer is mainly used for multithreading. If we click in the StringBuffer class and hold down the ctrl+7 selection append method to see the synchronized English shown in the figure, it means that it is used by multiple threads, but not in the StringBuilder class.
Conclusion:
The content of String cannot be modified, while the content of StringBuffer and StringBuilder can be modified.
Most of the functions of StringBuffer and StringBuilder are similar
StringBuffer adopts synchronous processing, which belongs to thread-safe operation, while StringBuilder does not adopt synchronous processing, which belongs to thread-safe operation.
Common methods of 2.StringBuilder and StringBuffer
The common methods of StringBuilder and StringBuffer are not found in String classes, such as append method, delete method, reserve method, insert method and so on.
Reverse method:
StringBuffer sb = new StringBuffer ("helloworld"); System.out.println (sb.reverse ()); / / the printed result is
Dlrowolleh
Delete method:
StringBuffer sb = new StringBuffer ("helloworld"); System.out.println (sb.delete (5,10)); / / print the result as
Hello
Insert method:
StringBuffer sb = new StringBuffer ("helloworld"); System.out.println (sb.delete (5,10) .insert (0, "Hello"); / / print the result as follows:
Hello, Hello
10. Understanding of string references
Many people think that if you pass a reference to a function and point to another object, you can solve "all problems", but this is not true. The following example illustrates the problem.
Code:
Public static void func (String str1,char [] chars) {str1= "hello"; chars [0] = 'glossy;} public static void main (String [] args) {String str = "abcd"; char [] chars = {' henceforth System.out.println (Arrays.toString (chars));} / / print the result as
Abcd
[g, e, l, l, o]
As a result, why did str not point to hello while chars changed from the original hello to gello? After learning about the string constant pool, we learned that the string constant pool can only store one string constant with the same content. Therefore, str1 in the func function is a formal parameter, and str1 points to the new object "hello", but the str in the main function still points to abcd. While chars is really based on the original array, the character of the 0 subscript is changed to'g', and the final printed result is [g, e, l, l, o] without any problem.
At this point, the study on "what is the use of the String class in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.