This blog will explain the String class in java in detail.
Create string
Common ways to construct String
//Mode 1 String str = "hello"; //Mode 2 String str1 = new String("Hello"); //Mode 3 char[] array = {'a', 'b', 'c'}; String str2 = new String(array);
be careful:
- String literal constants such as "hello" are also of type string.
- String is also a reference type.
Let's look at the following code:
public class TestDemo { public static void func(String s, char[] array) { s = "abc"; array[0] = 'x'; } public static void main(String[] args) { String str = "aaa"; char[] chars = {'b','b','c','c'}; func(str, chars); System.out.println(str); System.out.println(Arrays.toString(chars)); } }
The result of this code is:
Why did this happen? Let's take a look at the memory diagram of this code.
That's why the above results.
Constant pool
There are three types of constant pools: Class file constant pool, runtime constant pool and string constant pool.
Class file constant pool: used to store various literal and symbol references generated by the compiler.
Runtime constant pool: when the program loads the compiled bytecode file into the JVM, a runtime constant pool will be generated. The runtime constant pool is stored in the method area.
String constant pool: it mainly stores string constants, which is essentially a hash table.
string comparison
In Java, the equals method provided by the String class is generally used to compare whether two strings are equal. For example:
String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1.equals(str2));
The implementation results are:
be careful:
If the following code appears, an error will be reported:
String str1 = null; String str2 = new String("hello"); System.out.println(str1.equals(str2));
The implementation results are:
Immutable string
Let's look at this code first:
String str = "hello"; str = str + " world"; str += "!!!"; System.out.println(str);
The implementation results are:
This code indicates that it seems to modify the string, but it is not, but creates five variables:
If you really want to modify the string, you can do this:
String str = "hello"; str = "a" + str.substring(1); System.out.println(str);
The implementation results are:
Of course, you can also use the reflection method to modify:
String str = "hello"; // Get the value field in the String class This value matches the value in the String source code Field valueField = String.class.getDeclaredField("value"); // Set the access property of this field to true valueField.setAccessible(true); // Get the value attribute in str to char[] value = (char[]) valueField.get(str); // Modify the value of value value[0] = 'a'; System.out.println(str);
The implementation results are:
Why is String not variable?
-
Facilitate the implementation of String object pool. If the String is variable, the object pool needs to consider when to deep copy the String.
-
Immutable objects are thread safe.
-
Immutable objects are more convenient to cache hash code s. When used as key s, they can be saved to HashMap more efficiently.
Characters, bytes and strings
Characters and strings
The string contains a character array. String and char [] can be converted to each other.
No | Method name | type | describe |
---|---|---|---|
1 | public String(char value[]) | structure | Turns everything in the character array into a string |
2 | public String (char value[], int offset, int count) | structure | Changes the contents of a partial character array to a string |
3 | publilc char charAt(int index) | ordinary | Gets the character at the specified index position. The index starts at 0 |
4 | public char[] toCharArray() | ordinary | Returns a string as an array of characters |
Code example:
Merge characters into strings
char[] value = {'a','b','c','d','e'}; String str = new String(value); System.out.println(str);
The implementation results are:
Gets a character in a string
String str = "abcdef"; char val = str.charAt(3); System.out.println(val);
The implementation results are:
Combines some characters in a character array into a string
char[] value = {'a','b','c','d','e'}; String str = new String(value,1,3); System.out.println(str);
The implementation results are:
Convert string to character
String str = "abcdef"; char[] chars = str.toCharArray(); System.out.println(Arrays.toString(chars));
The implementation results are:
Judge whether the string is composed of numbers
public static void main(String[] args) { String str = "123a456"; System.out.println(isNumber(str)); } public static boolean isNumber(String s) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }
The implementation results are:
Bytes and strings
Bytes are often used in data transmission and encoding conversion. String can also be easily converted with byte [].
No | Method name | type | describe |
---|---|---|---|
1 | public String(byte bytes[]) | structure | Change byte array to character array |
2 | public String(byte bytes[], int offset, int length) | structure | Changes the contents of a partial byte array into a string |
3 | public byte[] getBytes() | ordinary | Returns a string as a byte array |
4 | public byte[] getBytes(String charsetName)throws UnsupportedEncodingException | ordinary | Code conversion processing |
Code example:
Realize the conversion between string and byte array
byte[] bytes = {97,98,99,100,101,102}; String str = new String(bytes); System.out.println(str); System.out.println("========================"); String str2 = "abcdefg"; byte[] bytes1 = str2.getBytes(); System.out.println(Arrays.toString(bytes1));
The implementation results are:
Code conversion processing
String str2 = "Hello"; byte[] bytes1 = str2.getBytes("utf-8"); System.out.println(Arrays.toString(bytes1));
The execution result is:
Summary
Byte [] is used to process strings byte by byte. It is suitable for network transmission and data storage. It is more suitable for binary data operation.
char [] handles strings one character by one, which is more suitable for text data operation, especially when Chinese is included.
String common operations
string comparison
No | Method name | type | describe |
---|---|---|---|
1 | public boolean equals(Object anObject) | ordinary | Case sensitive comparison |
2 | public boolean equalsIgnoreCase(String anotherString) | ordinary | Case insensitive comparison |
3 | public int compareTo(String anotherString) | ordinary | Compare the size relationship between two strings |
Code example:
String str1 = "hello"; String str2 = "HELLO"; System.out.println(str1.equals(str2)); System.out.println(str1.equalsIgnoreCase(str2)); System.out.println(str1.compareTo(str2));
The operation result is:
In the String class, compareTo() method is a very important method. This method returns an integer, and the data will return three types of contents according to the size relationship:
- Equal: return 0
- Less than: the returned content is less than 0
- Greater than: the returned content is greater than 0
String lookup
No | Method name | type | describe |
---|---|---|---|
1 | public boolean contains(CharSequence s) | ordinary | Determine whether a substring exists |
2 | public int indexOf(String str) | ordinary | Find the position of the specified string from the beginning, and find the starting index of the return position. If not, return - 1 |
3 | public int indexOf(String str, int fromIndex) | ordinary | Finds the substring position from the specified position |
4 | public int lastIndexOf(String str) | ordinary | Find substring position from back to front |
5 | public int lastIndexOf(String str, int fromIndex) | ordinary | Find from the specified position from back to front |
6 | public boolean startsWith(String prefix) | ordinary | Determines whether to start with the specified string |
7 | public boolean startsWith(String prefix, int toffset) | ordinary | Judge whether to start with the specified string from the specified position |
8 | public boolean endsWith(String suffix) | ordinary | Determines whether to end with the specified string |
Code example:
String str1 = "abcdefabcdef"; String str2 = "bcd"; System.out.println(str1.contains(str2)); System.out.println(str1.indexOf(str2,3)); System.out.println(str1.lastIndexOf(str2)); System.out.println(str1.startsWith("abba")); System.out.println(str1.endsWith("ef"));
The implementation results are:
String substitution
No | Method name | type | describe |
---|---|---|---|
1 | public String replaceAll(String regex, String replacement) | ordinary | Replace all specified contents |
2 | public String replaceFirst(String regex, String replacement) | ordinary | Replace first content |
Code example:
String str1 = "abcabcabcddee"; System.out.println(str1.replace('a','x')); System.out.println(str1.replace("ab","xy")); System.out.println(str1.replaceAll("abc","y")); System.out.println(str1.replaceFirst("abc","pppp"));
The implementation results are:
String splitting
No | Method name | type | describe |
---|---|---|---|
1 | public String[] split(String regex) | ordinary | Split all strings |
2 | public String[] split(String regex, int limit) | ordinary | Split the string part, and the length of the array is the limit limit |
Code example:
String str = "name=zhangsan&age=19"; String[] strings = str.split("&"); for (String s:strings) { System.out.println(s); } System.out.println("================================="); for (String s:strings) { String[] ss = s.split("="); for (String tmp:ss) { System.out.println(tmp); } }
The implementation results are:
matters needing attention:
- The characters "|", "*", "+" must be preceded by the escape character "\ \".
- If it's "\", it has to be written as "\ \".
- If there are multiple separators in a string, you can use "|" as a hyphen.
For example:
String str = "192.68.1.1"; String[] strings = str.split("\\."); for (String s:strings) { System.out.println(s); } System.out.println("=========================="); String str1 = "192.68.1.1"; String[] strings1 = str1.split("\\.",3); for (String s:strings1) { System.out.println(s); } System.out.println("++++++++++++++++++++++++++"); String string = "java30 12&21#hello"; String[] strings2 = string.split(" |&|#"); for (String s:strings2) { System.out.println(s); }
The implementation results are:
String interception
No | Method name | type | describe |
---|---|---|---|
1 | public String substring(int beginIndex) | ordinary | Truncates from the specified index to the end |
2 | public String substring(int beginIndex, int endIndex) | ordinary | Intercept part of the content |
matters needing attention:
- Index starts at 0.
- Pay attention to the writing method of the interval before closing and after opening. substring(0,5) indicates the character with subscript 0 and not with subscript 5.
Code example:
String str = "abcdefg"; System.out.println(str.substring(5)); System.out.println(str.substring(2,6));
The implementation results are:
Other operation methods
No | Method name | type | describe |
---|---|---|---|
1 | public String trim() | ordinary | Remove the left and right spaces in the string and keep the middle space |
2 | public String toUpperCase() | ordinary | Convert string to uppercase |
3 | public String toLowerCase() | ordinary | String to lowercase |
4 | public native String intern() | ordinary | String pool operation |
5 | public String concat(String str) | ordinary | String connection, which is equivalent to "+", and the spliced objects will not enter the pool |
6 | public int length() | ordinary | Get string length |
7 | public boolean isEmpty() | ordinary | Judge whether it is an empty string, but it is not null, but the length is 0 |
StringBuffer and StringBuilder
First, let's review the characteristics of String class:
Any String constant is a String object, and once declared, the String constant cannot be changed. If the content of the object is changed, only the reference point will be changed. Generally speaking, the operation of String is relatively simple. However, due to the immutability of String, in order to facilitate the modification of String, StringBuffer and StringBuilder classes are provided. Most of the functions of StringBuffer and StringBuilder are the same. Use "+" in String to connect strings, but this operation needs to be changed to the append() method in StringBuilder class.
Let's take a look at StringBuilder first,
sb.append("abcdef"); sb.append("123"); System.out.println(sb); System.out.println("========================"); System.out.println(sb.reverse());
The operation result is:
Note: String and StringBuffer classes cannot be converted directly. If you want to convert each other, you can adopt the following principles:
-
Change String to StringBuffer: use the construction method or append() method of StringBuffer.
-
Change StringBuffer to String: call toString() method.
For example:
public static StringBuilder func() { String str = "abcd"; return new StringBuilder(str); } public static String fun() { StringBuilder sb = new StringBuilder(); return sb.toString(); }
Differences among String, StringBuffer and StringBuilder:
-
The contents of String cannot be modified. The contents of StringBuffer and StringBuilder can be modified.
-
Most functions of StringBuffer and StringBuilder are similar.
-
StringBuffer adopts synchronous processing, which belongs to thread safe operation; StringBuilder does not adopt synchronous processing, which belongs to thread unsafe operation.
ending
This is the end of this blog.
Last blog: Java learning journey (13) -- polymorphism
Next blog: Java learning journey (15) -- exceptions