Use code to "deeply" understand the basic java knowledge that 90% of beginners do not understand - Java core classes String, StringBuilder, StringJoiner, wrapper type, JavaBean

Hello, everyone. In this issue, I will continue to review the basic knowledge of Java in the code. You can knock it yourself to deepen your understanding. According to this knowledge, I also sorted out a map. Basically, each knowledge point has notes and detailed explanations

Click here to add a group to get information

String

In Java, String is a reference type, and it is also a class. However, the java compiler has a special treatment for strings, that is, you can directly use "..." to represent a String.

Create: String s1 = "Hello"

In Java, String is a reference type, and it is also a class. However, the java compiler has special processing for strings, that is, you can directly use "..." to represent a String:

String s1 = "Hello!";

In fact, the String is represented by a char [] array inside the String. Therefore, it is possible to write it as follows:

String s2 = new String(new char[] {'H', 'e', 'l', 'l', 'o', '!'});

An important feature of Java strings is that strings are immutable. This immutability is realized through the internal private final char [] field and without any method of modifying char [].

compare

s1.equals(s2)

When comparing two strings, you must always use the equals() method.
To ignore the case comparison, use the equalsIgnoreCase() method.

search

s1.contain(s2) s1.indexOf(s2) / s1.lastIndexOf(s2) / s1.statsWith(s2) / s1.endWith(s2)

// Include substring:
"Hello".contains("ll"); // true
"Hello".indexOf("l"); // 2
"Hello".lastIndexOf("l"); // 3
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true

extract

s1.substring(index1, index2)
"Hello".substring(2); // "llo"
"Hello".substring(2, 4); "ll"

Remove leading and trailing blanks

s1.trim() / s1.strip()

Use the trim() method to remove white space characters from the beginning and end of a string. White space characters include spaces, \ t, \ r \ n:

"  \tHello\r\n ".trim(); // "Hello"

Note: trim() does not change the contents of the string, but returns a new string.
Another strip() method can also remove white space characters at the beginning and end of a string. Unlike trim(), the Chinese space character \ u3000 will also be removed:

"\u3000Hello\u3000".strip(); // "Hello"
" Hello ".stripLeading(); // "Hello "
" Hello ".stripTrailing(); // " Hello"

String also provides isEmpty() and isBlank() to judge whether the string is empty or blank:

"".isEmpty(); // true because the string length is 0
"  ".isEmpty(); // false because the string length is not 0
"  \n".isBlank(); // true because it contains only white space characters
" Hello ".isBlank(); // false because it contains non white space characters

Replace substring

s1.replace(s2, s3) / s1.replaceAll(regex)

There are two ways to replace substrings in a string. One is to replace according to characters or strings:

String s = "hello";
s.replace('l', 'w'); // "hewwo", all characters' l 'are replaced by' w '
s.replace("ll", "~~"); // "he~~o", all substrings "ll" are replaced with "~ ~"

The other is to replace by regular expression:

String s = "A,,B;C ,D";
s.replaceAll("[\\,\\;\\s]+", ","); // "A,B,C,D"

The above code uniformly replaces the matching substring with "," through regular expression.

division

s1.split(regex)

To split a string, use the split() method and pass in a regular expression:

String s = "A,B,C,D";
String[] ss = s.split("\\,"); // {"A", "B", "C", "D"}

Splicing

String.join("Splice symbol", String[])

Splicing strings uses the static method join(), which connects the string array with the specified string:

String[] arr = {"A", "B", "C"};
String s = String.join("***", arr); // "A***B***C"

Convert basic type to String

String.valueOf(Basic type)  

To convert any base or reference type to a string, you can use the static method valueOf(). This is an overloaded method. The compiler will automatically select the appropriate method according to the parameters:

String.valueOf(123); // "123"
String.valueOf(45.67); // "45.67"
String.valueOf(true); // "true"
String.valueOf(new Object()); // Similar to Java lang. Object@636be97c

Convert String to base type

Integer.parseInt(s1) / Double.parseDouble(s1) / Boolean.parseBoolean(s1)

To convert a string to another type, you need to change it as appropriate.
For example, convert a string to type int:

int n1 = Integer.parseInt("123"); // 123
int n2 = Integer.parseInt("ff", 16); // Hexadecimal conversion, 255

Convert string to boolean type:

boolean b1 = Boolean.parseBoolean("true"); // true
boolean b2 = Boolean.parseBoolean("FALSE"); // false

String -> char[]

char[ ] cs = s1.toCharArray()  

String -> char[]

char[ ] cs = s1.toCharArray()  

When creating a new String instance through new String(char []), it will not directly reference the incoming char [] array, but will copy a copy. Therefore, modifying the external char [] array will not affect the char [] array inside the String instance, because these are two different arrays.

code

byte[] b1 = s1.getBytes("Some coding method")

decode

String s1 = new String(b1, "Some coding method")

StringBuilder

StringBuilder is a variable object, which is used to splice strings efficiently;
StringBuilder can support chain operation. The key to realize chain operation is to return the instance itself;
StringBuffer is a thread safe version of StringBuilder and is rarely used now.

establish

StringBuilder sb = new StringBuilder(Buffer size);

Write string

sb.append(s1).sappend(s2)...

In order to splice strings efficiently, the Java standard library provides StringBuilder, which is a variable object and can pre allocate buffers. In this way, when adding characters to StringBuilder, new temporary objects will not be created:

StringBuilder sb = new StringBuilder(1024);
for (int i = 0; i < 1000; i++) {
    sb.append(',');
    sb.append(i);
}
String s = sb.toString();
StringBuilder Chain operation can also be carried out:
public class Main {
    public static void main(String[] args) {
        var sb = new StringBuilder(1024);
        sb.append("Mr ")
          .append("Bob")
          .append("!")
          .insert(0, "Hello, ");
        System.out.println(sb.toString());
    }
}

Delete string

sb.delete(start_index, end_index)

transformation

String s1 = sb.toString()

StringJoiner

StringJoiner is responsible for splicing the contents of arrays with separators, and can also specify "beginning" and "end":

public class Main {
    public static void main(String[] args) {
        String[] names = {"Bob", "Alice", "Grace"};
        var sj = new StringJoiner(", ", "Hello ", "!");
        for (String name : names) {
            sj.add(name);
        }
        System.out.println(sj.toString());
    }
}

Operation results:

Hello Bob, Alice, Grace!

establish

var sj = new StringJoiner(Separator, Start symbol, End symbol)

Write string

sj.add(s1)

transformation

String s1 = sb.toString()

Packaging type

Basic typeCorresponding reference type
booleanjava.lang.Boolean
bytejava.lang.Byte
shortjava.lang.Short
intjava.lang.Integer
longjava.lang.Long
floatjava.lang.Float
doublejava.lang.Double
charjava.lang.Character

Note: Auto boxing and auto unpacking only occur in the compilation stage in order to write less code.
Boxing and unpacking will affect the execution efficiency of the code, because the compiled class code strictly distinguishes between basic types and reference types. In addition, NullPointerException may be reported during automatic unpacking:

public class Main {
    public static void main(String[] args) {
        Integer n = null;
        int i = n;
    }
}

The comparison of packing types must use equals();

Automatic packing

Integer n = 100; // The compiler automatically uses integer valueOf(int)

This assignment method that directly changes int to Integer is called Auto Boxing

Automatic unpacking

int x = n; // The compiler automatically uses integer intValue()

The assignment method of changing Integer into int is called auto unpacking.

Binary conversion

int x2 = Integer.parseInt("100", 16); // 256, because it is parsed in hexadecimal

The Integer class itself also provides a large number of methods. For example, the most commonly used static method parseInt() can parse a string into an Integer:

int x1 = Integer.parseInt("100"); // 100
int x2 = Integer.parseInt("100", 16); // 256, because it is parsed in hexadecimal

Integer can also format integers into strings of specified base numbers:

// Integer:
public class Main {
    public static void main(String[] args) {
        System.out.println(Integer.toString(100)); // "100" is represented as decimal
        System.out.println(Integer.toString(100, 36)); // "2s" is expressed in hexadecimal 36
        System.out.println(Integer.toHexString(100)); // "64" means hexadecimal
        System.out.println(Integer.toOctalString(100)); // "144", expressed as octal
        System.out.println(Integer.toBinaryString(100)); // "1100100" indicates binary
    }
}

Static variable

Java wrapper types also define some useful static variables

// Boolean has only two values true/false, and its wrapper type only needs to reference the static fields provided by Boolean:
Boolean t = Boolean.TRUE;
Boolean f = Boolean.FALSE;
// Max / min value that int can represent:
int max = Integer.MAX_VALUE; // 2147483647
int min = Integer.MIN_VALUE; // -2147483648
// Number of bit s and byte s occupied by long type:
int sizeOfLong = Long.SIZE; // 64 (bits)
int bytesOfLong = Long.BYTES; // 8 (bytes)

Number

All wrapper types of integers and floating-point numbers are inherited from Number. Therefore, it is very convenient to obtain various basic types directly through wrapper types:

// Up to Number:
Number num = new Integer(999);
// Get byte, int, long, float, double:
byte b = num.byteValue();
int n = num.intValue();
long ln = num.longValue();
float f = num.floatValue();
double d = num.doubleValue();

JavaBean

In Java, many class definitions conform to such specifications:
Several private instance fields;
Use the public method to read and write instance fields.

public class Person {
    private String name;
    private int age;
    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return this.age; }
    public void setAge(int age) { this.age = age; }
}

If the read-write method complies with the following naming conventions:

// Read method:
public Type getXyz()
// Write method:
public void setXyz(Type value)

Then this class is called a JavaBean:
If the above field is XYZ, the read-write method names start with get and set respectively, followed by the field name XYZ starting with an uppercase letter. Therefore, the two read-write method names are getXyz() and setXyz() respectively.
The boolean field is special. Its reading method is generally named isXyz():

// Read method:
public boolean isChild()
// Write method:
public void setChild(boolean value)

We usually call a set of corresponding read methods (getter s) and write methods (setter s) as properties.
JavaBean is a class that conforms to the naming convention. It defines attributes through getter s and setter s;
Attribute is a common name, not specified in Java syntax;
You can use IDE to quickly generate getter s and setter s;
Using introspector Getbeaninfo () can get the attribute list.

Finally, I wish you success in your studies as soon as possible, get a satisfactory offer, get a quick promotion and raise, and reach the peak of your life. If you can, please give me a third company to support me. I'll see you next time

Keywords: Java string javabean StringBuilder

Added by xudzh on Wed, 22 Dec 2021 01:52:30 +0200