2021-06-16 Java Basics – String class details

This article reprints the lobyte article directory one, creates the string

  1. Direct assignment (common)
  2. new String
  3. Character array to String

4. The difference between the two types of object instantiation in the String class Compare strings directly 2. Store strings in memory 3. String constant pool 4. String compare equals 5. Understand string immutable 6. Manually pool intern() 3. Character to string 2. String to character 3. Byte and string 4. Encoding mode 5. Common operations on strings 1. Compare strings 2. Search strings 3. String substitution 4. String splitting 5. String interception 6. Other operations 5. String reverse() 3. Delete the specified range of data delete() 4. There are many different ways to create a string. There are three common ways to create a string

  1. Direct assignment (common)

String str = “hello world !” ; 1 2. new String String str = new String(“hello world !” ); String char[] array = {‘a’, ‘b’, ‘c’}; String str = new String(array); But in the future, the first method is usually used. Note:

“Hello” is a String literal constant of type String. String is also a reference type. String STR =”Hello” 4. The difference between the two object instantiations in String is direct assignment: only a chunk of heap memory is allocated, and the String object is automatically saved in the object pool for future use. Constructor: creates two heap memory Spaces and does not automatically store them in the object pool. The bytes can be pooled manually using intern(). == == == == == == == == == ==

Code:

public static void main(String[] args) {         String str1 = “hello”;         String str2 = new String(“hello”);         System.out.println(str1 == str2);

String str3 = “he”+”llo”; String str3 = “hello”; System.out.println(str1 == str3);

        String str4 = “he”;         String str5 = “llo”;         String str6 = str4+str5;         System.out.println(str1 == str6);

String str7 = “he”+new String(“llo”); System.out.println(str1 == str7); } 12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

We know that String is a reference, so STR stores an address. So you’re comparing addresses. As soon as it’s new it opens up memory on the heap, so it’s not equal. The following is a simple memory map to determine whether strings are equal or not.

Let’s look at how strings are stored in memory to determine equality

Note: 1. As long as new will open up memory on the heap, then must not equal. 2. Only one copy of the same string will be stored in the string constant pool.

3. The String constant pool String class is designed using a shared design pattern

There is actually an object pool (string constant pool) that is automatically maintained under the JVM

If a String object is instantiated using the direct assignment mode, the instantiated object (String content) will be automatically saved to the object pool. If you continue to use the directly assigned schema to declare String objects next time, if there is something specified in the object pool, it will be referenced directly. If not, a new String object will be created and stored in the object pool for next use. To compare strings to equals in Java, we use the equals method provided by strings

String str1 = new String(“Hello”); String str2 = new String(“Hello”); System.out.println(str1.equals(str2)); // System.out.println(str2.equals(str1)); = 1, 2, 3, 4, 5, 6 equals = 1, 2, 3, 4, 6

String str = new String(“Hello”); System.out.println(str.equals(“Hello”)); System.out.println(“Hello”.equals(STR)); 1, 2, 3, 4, 5 In the code above, which is better? If STR is null, the code for method one will throw an exception, but method two will not

String str = null; System.out.println(str.equals(“Hello”)); / / execution results throw Java. Lang. NullPointerException is way / / 2 System. Out. The println (” Hello “. The equals (STR)); // Execute result false

1, 2, 3, 4, 5, 6, 7 Note: literal constants like “Hello” are essentially strings and can be used with equals and other String methods

5. Understand the Immutable nature of Strings STRINGS are immutable objects. Its contents are immutable. The internal implementation of the String class is also based on char[], but the String class does not provide set methods to modify the internal character array.

Code examples:

String str = “hello” ; str = str + ” world” ; str += “!!!” ; System.out.println(str); // Result Hello world!! Operations like 1, 2, 3, 4, 5, and 6, which appear to modify the string, are not. Memory changes are as follows:

After +=, STR prints a different result, but instead of changing the String itself, STR references other objects.

Review quote:

A reference is a pointer that holds an address. We need to distinguish whether the current modification has changed the contents of the memory corresponding to the address or the address stored in the reference.

We know that string constants are stored in the string constant pool, and that new memory is created on the heap. The String intern() method, on the other hand, inserts String objects into the String constant pool

// This String constant is not stored in the object pool. String str1 = “hello”; String str2 = new String(“hello”) ; System.out.println(str1 == str2); False String str1 = “hello”; String str2 = new String(“hello”).intern() ; System.out.println(str1 == str2); String 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 if str2 does not intern(), it points to the new String on the heap. If “hello” is not in the string constant pool when you call intern(), it will be put into the pool.

Character byte and string 1. Character to string

Code examples:

char[] array = {‘h’,’e’,’l’,’l’,’o’}; String str1 = new String(array); String str2 = new String(array,1,2); System.out.println(str1); System.out.println(str2); //hello //el 1 2 3 4 5 6 7 8 And the subscript must not cross the boundary!

2. String conversion

To get a character from a string:

String str = “hello”; char ch = str.charAt(4); System.out.println(ch); O 1 2 3 4 5 string to character array example code:

String str = “hello”; char[] array = str.toCharArray(); for (char s : array) { System.out.print(s+” “); } 1 2 3 4 5 Run result

3. Bytes and strings

The usage is similar to the above code example:

97,98,99,100 byte [] bytes = {}; String STR = new String(bytes,1,3); System.out.println(str); String str2 = “abcd”; byte[] bytes1 = str2.getBytes(); System.out.println(Arrays.toString(bytes1)); 1 2 3 4 5 6 7 Run results

4. Coding method

Running results:

Common encoding methods include UTF-8 and GBK, but generally only affect Chinese characters.

When to use byte[] and when to use char[]?

Byte [] is a String processed byte by byte, which is suitable for network transmission and data storage scenarios. Char [] is more suitable for manipulating binary data. Char [] is more suitable for manipulating text data, especially if Chinese is included: text data vs binary data

A simple and crude way to distinguish is to open notepad can read the contents of the inside. If you can read it, it’s textual data (e.g..java files), if you can’t, it’s binary data (e.g..class files).

We used the equals() method provided by the String class above, which is itself a case-sensitive equality check. In addition to this method, the String class provides the following comparison operations:

Code examples:

        String str = “abcd”;         System.out.println(“abcd”.equals(str));

System.out.println(“Abcd”.equalsIgnoreCase(str)); 1 2 3 4 5 6 7 **compareTo()** The compareTo() method is described in detail in the previous blog, so I won’t go into details here. The compareTo() method is a very important one in the String class. It returns an integer that returns three types of contents depending on size:

Equal: returns 0. Less: Returns contents less than 0. Greater: returns contents greater than 0. 2. String search From a complete string can determine whether the specified content exists, for the search method has the following definition:

Code examples:

String str = “abcdefg”; Find a substring System. Out. Println (STR) contains (efg)); 1 system.out.println (str.indexof (“d”)); Println (str.indexof (“d”,2)); Println (str.lastIndexof (“fg”))); Println (str.startswith (” ABC “)); Println (str.startswith (“de”, 3)); system.out.println (str.startswith (“de”, 3)); 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 all use the String class to specify the name of the method, and just put the value back.

3. String replacement Replace the existing string data with a specified new string as follows:

Code examples:

String str = “helloworld” ; System.out.println(str.replaceAll(“l”, “!” )); System.out.println(str.replaceFirst(“l”, “!” )); 1 2 3 Running results

Note that if you replace special characters, you need to use escape characters. Code examples:

String str1 = “192\168\1\1” ; System.out.println(str1.replaceAll(“\\”, “+”)); String str2 = ; System.out.println(str2.replaceAll(“\.”, “%20”)); 1, 2, 3, 4 Running results

Note: Since strings are immutable objects, substitution does not modify the current string, but produces a new string.

4. String splitting A complete string can be divided into several substrings according to the specified delimiter.

Code examples:

String str1 = “192.168.1.1”; String[] array = str1.split(“\.”); for (String s : array) { System.out.println(s); } 1 2 3 4 5 Run result

Note: the following code cannot be split

String str1 = “192\168\1\1” ; String[] array = str1.split(“\\”); for (String s : array) { System.out.println(s); } 1 2 3 4 5

Because \ is escaped into an octal number followed by two or three digits.

Matters needing attention:

Character “|”, “*”, “+” with a “have to add escape character,”. And if it is “”,” “you have to write. If have more than one separator in a string, “|” can be used as a hyphen. Examples of code to split multiple times:

String str = “name=zhangsan&age=18”; String[] result = str.split(“&|=”) ; for (String s : result) { System.out.println(s); } 1 2 3 4 5

5. String interception Intercepts portions of a complete string.

Code examples:

String str = “abcdef”; System.out.println(str.substring(3)); System.out.println(str.substring(2, 4)); Def CD 1 2 3 4 5 6

Substring (0, 5) indicates a character with index 0 but does not contain index 6. Other operation methods

These are relatively simple, just look them up when you use them.

StringBuffer and StringBuilder

Any String constant is a String, and a String constant, once declared, cannot be changed. If you change the content of the object, all you change is what it refers to.

Strings are generally easy to operate on, but because of the immutable nature of strings, classes StringBuffer and StringBuilder are provided to make it easier to modify strings. StringBuffer and StringBuilder are mostly the same, with minor differences.

1. The append() method uses “+” in String to concatenate strings, but this operation needs to be changed to append() in the StringBuffer class:

Public synchronized StringBuffer append

StringBuffer str1 = new StringBuffer(“abcd”); StringBuilder str2 = new StringBuilder(“abcd”); str1.append(123); str2.append(“hij”); System.out.println(str1); System.out.println(str2); 1 2 3 4 5 6

StringBuffer and StringBuilder have much of the same functionality, and their append() methods can concatenate various data types.

Note:

The main difference between a String and a StringBuffer is that the contents of a String cannot be modified, whereas the contents of a StringBuffer can be modified. StingBuffer is considered for frequent string modifications.

Because String concatenates temporary objects through + concatenation, StringBuffer and StringBuilder concatenate only the current object.

2. String reverse() Example of this code:

StringBuffer str1 = new StringBuffer(“abcdefg”); StringBuilder str2 = new StringBuilder(“654321”); System.out.println(str1.reverse()); System.out.println(str2.reverse()); 1 2 3 4 Operating results:

3. Delete a specified range of data

StringBuffer str1 = new StringBuffer(“abcdefg”); StringBuilder str2 = new StringBuilder(“654321”); System.out.println(str1.delete(2, 5)); System.out.println(str2.delete(4, 6)); 1 2 3 4 Operating results:

Insert ();

StringBuffer str1 = new StringBuffer(“abcdefg”); StringBuilder str2 = new StringBuilder(“654321″); Str1. insert(0,” how are you “).delete(0,1); System.out.println(str1); System.out.println(str2.delete(0, 3).insert(0, “Hello world “)); 1 2 3 4 5 Operating results:

Take a look at the append methods of StringBuffer and StringBuilder

String concatenation produces a temporary object, but the latter two only return a reference to the current object each time. 2.String plus concatenation is optimized into a StringBuilder. 4.StringBuffer is usually used if multiple threads are not involved.

If concatenation of strings is involved in the future, be sure to use StringBuffer and the Append () method of StringBuilder 2. Note the difference between the two object instantiations in the String class. 3. Only one copy of the same String is stored in the String constant pool

Ps needs self-study video attention B: free to receive”