Java learning journey -- String

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?

  1. Facilitate the implementation of String object pool. If the String is variable, the object pool needs to consider when to deep copy the String.

  2. Immutable objects are thread safe.

  3. 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.

NoMethod nametypedescribe
1public String(char value[])structureTurns everything in the character array into a string
2public String (char value[], int offset, int count)structureChanges the contents of a partial character array to a string
3publilc char charAt(int index)ordinaryGets the character at the specified index position. The index starts at 0
4public char[] toCharArray()ordinaryReturns 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 [].

NoMethod nametypedescribe
1public String(byte bytes[])structureChange byte array to character array
2public String(byte bytes[], int offset, int length)structureChanges the contents of a partial byte array into a string
3public byte[] getBytes()ordinaryReturns a string as a byte array
4public byte[] getBytes(String charsetName)throws UnsupportedEncodingExceptionordinaryCode 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

NoMethod nametypedescribe
1public boolean equals(Object anObject)ordinaryCase sensitive comparison
2public boolean equalsIgnoreCase(String anotherString)ordinaryCase insensitive comparison
3public int compareTo(String anotherString)ordinaryCompare 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:

  1. Equal: return 0
  2. Less than: the returned content is less than 0
  3. Greater than: the returned content is greater than 0

String lookup

NoMethod nametypedescribe
1public boolean contains(CharSequence s)ordinaryDetermine whether a substring exists
2public int indexOf(String str)ordinaryFind the position of the specified string from the beginning, and find the starting index of the return position. If not, return - 1
3public int indexOf(String str, int fromIndex)ordinaryFinds the substring position from the specified position
4public int lastIndexOf(String str)ordinaryFind substring position from back to front
5public int lastIndexOf(String str, int fromIndex)ordinaryFind from the specified position from back to front
6public boolean startsWith(String prefix)ordinaryDetermines whether to start with the specified string
7public boolean startsWith(String prefix, int toffset)ordinaryJudge whether to start with the specified string from the specified position
8public boolean endsWith(String suffix)ordinaryDetermines 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

NoMethod nametypedescribe
1public String replaceAll(String regex, String replacement)ordinaryReplace all specified contents
2public String replaceFirst(String regex, String replacement)ordinaryReplace 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

NoMethod nametypedescribe
1public String[] split(String regex)ordinarySplit all strings
2public String[] split(String regex, int limit)ordinarySplit 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:

  1. The characters "|", "*", "+" must be preceded by the escape character "\ \".
  2. If it's "\", it has to be written as "\ \".
  3. 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

NoMethod nametypedescribe
1public String substring(int beginIndex)ordinaryTruncates from the specified index to the end
2public String substring(int beginIndex, int endIndex)ordinaryIntercept part of the content

matters needing attention:

  1. Index starts at 0.
  2. 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

NoMethod nametypedescribe
1public String trim()ordinaryRemove the left and right spaces in the string and keep the middle space
2public String toUpperCase()ordinaryConvert string to uppercase
3public String toLowerCase()ordinaryString to lowercase
4public native String intern()ordinaryString pool operation
5public String concat(String str)ordinaryString connection, which is equivalent to "+", and the spliced objects will not enter the pool
6public int length()ordinaryGet string length
7public boolean isEmpty()ordinaryJudge 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

Keywords: Java Back-end

Added by o3d on Mon, 07 Mar 2022 09:43:18 +0200