Common Java classes

Posted by schajee on Tue, 21 Apr 2020 14:51:29 +0200

1, String class

Use of java.lang.String class

(1) Overview

String: string, represented by a pair of "" causes.

  1. String declared final, cannot be inherited

  2. String implements the Serializable interface: indicates that strings support serialization. Implemented the compatible interface: indicates that string can compare sizes

  3. final char[] value is defined inside String to store String data

  4. String: represents an immutable sequence of characters. Abbreviation: immutability.


    4.1. When reassigning a string, you need to override the assigned memory area assignment, instead of using the original value.

    4.2. When the existing string is connected, it is also necessary to specify the memory area assignment again, and the original value cannot be used for assignment.

    4.3. When calling the replace() method of String to modify the specified character or String, it is also necessary to re specify the memory area assignment, instead of using the original value for assignment.

  5. By literal means (different from the way new assigns a value to a string, in which case the string value is declared in the string constant pool).

  6. A String with the same content (return true by comparing with equals() of String class) will not be stored in the String constant pool.

(2) Properties of String

String class: represents a string. All string literals in Java programs, such as "abc," are implemented as instances of this class. String is a final class that represents an immutable sequence of characters. A string is a constant, represented by double quotes. Their values cannot be changed after creation. The character content of the string object is stored in a character array value [].

String source Builder:

public final class String
    implements, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

1. The immutability of string

1.1 Description:

  1. When reassigning a string, you need to override the specified memory area assignment, instead of using the original value.
  2. When the existing string is connected, it is also necessary to specify the memory area assignment again, instead of using the original value.
  3. When you call the replace() method of String to modify the specified character or String, you also need to re specify the memory area assignment. You cannot use the original value for assignment.

1.2 code example:

String s1 = "abc";//Through the definition of literal quantity
String s2 = "def";
s1 = "hello";

System.out.println(s1 == s2); //false compares the address values of s1 and s2



String s3 = "abc";
s3 += "def";


String s4 ="test";
String s5 = s4.replace("t","b");

1.3 diagram analysis:

2. String instantiation method

2.1 description of implementation mode:

  • Mode 1: defined by literal quantity
  • Mode 2: through new + constructor

Interview questions:

String s = new String("abc"); how many objects are created in memory? Two: one is the new structure in the heap space, the other is the data in the constant pool corresponding to char []: "abc"

2.2 code example:

//By literal definition: at this time, the data Java EE of s1 and s2 is declared in the string constant pool in the method area.
String s1 = "javaEE";
String s2 = "javaEE";
//Through the way of new + constructor: the address values saved in s3 and s4 at this time are the corresponding address values after the data has opened space in the heap space.
String s3 = new String("javaEE");
String s4 = new String("javaEE");

System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false

What's the difference between String str1 = "abc"; and String str2= new String("abc")?

Memory resolution of new String object

3. String splicing method assignment comparison

3.1 Description:

  1. The splicing result of constant and constant is in constant pool. And there will be no constants of the same content in the constant pool.
  2. As long as one of them is a variable, the result is in the heap.
  3. If the concatenated result calls the intern() method, the return value is in the constant pool

3.2 code example

String s1 = "javaEE";
String s2 = "hadoop";

String s3 = "javaEEhadoop";
String s4 = "javaEE" + "hadoop";
String s5 = s1 + "hadoop";
String s6 = "javaEE" + s2;
String s7 = s1 + s2;

System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false

String s8 = s6.intern();//Returns the value of "Java eehadoop" that already exists in the constant value used by s8
System.out.println(s3 == s8);//true
String s1 = "javaEEhadoop";
String s2 = "javaEE";
String s3 = s2 + "hadoop";
System.out.println(s1 == s3);//false

final String s4 = "javaEE";//s4: constant
String s5 = s4 + "hadoop";
System.out.println(s1 == s5);//true

Memory resolution

4. String use trap

  • String s1="a";

    Description: a string with literal "a" is created in the string constant pool.

  • s1=s1+"b"

    Note: in fact, the original "a" string object has been discarded, and now a string s1+"b" (also known as "ab") is generated in the heap space. If you perform these operations to change the string content multiple times, a large number of copy string objects will remain in memory, reducing efficiency. If such an operation is placed in a loop, it will greatly affect the performance of the program.

  • String s2="ab"; Description: directly create a string with literal value "ab" in the string constant pool.

  • String s3="a"+"b"; note: s3 points to the string of "ab" that has been created in the string constant pool.

  • String s4=s1.intern(); note: after calling intern(), S1 object in heap space will assign the existing "ab" string in constant pool to s4.

5. Common methods of string class

5.1 string operation

Operation character:

  1. int length(): return string length: return value.length
  2. char charAt(int index): returns the character return value at an index [index]
  3. boolean isEmpty(): judge whether it is an empty string: return value.length == 0
  4. String toLowerCase(): use the default locale to convert all characters in string to lowercase
  5. String toUpperCase(): use the default locale to convert all characters in string to uppercase
  6. String trim(): returns a copy of the string, ignoring leading and trailing whitespace
  7. boolean equals(Object obj): compare whether the contents of strings are the same
  8. Boolean equals ignorecase (string another string): similar to the equals method, case is ignored
  9. String concat(String str): connects the specified string to the end of the string. Equivalent to "+"
  10. Int CompareTo (string another string): compare the sizes of two strings
  11. String substring(int beginIndex): returns a new string from the beginIndex to the last substring of the string.
  12. String substring(int beginIndex, int endIndex): returns a new string, which is a substring from beginIndex to endindex (not included).

Code example:

public void test2() {
    String s1 = "helloword";

    String s2 = "HELLOword";

    String s3 = " hello word ";
    System.out.println(s3.trim());//hello word
    String s4 = "helloword";
    String s5 = "hello";
    System.out.println(s5.compareTo(s4));//-Returns 0 when 4 is equal and negative when small

    System.out.println(s4.substring(5, 9));//word, value range left open right closed


Judging character:

  1. boolean endsWith(String suffix): tests whether the string ends with the specified suffix
  2. boolean startsWith(String prefix): test whether the string starts with the specified prefix
  3. boolean startsWith(String prefix, int toffset): test whether the substring of this string starting from the specified index starts with the specified prefix
public void test3() {
    String s1 = "javaEE";
    System.out.println(s1.startsWith("EE", 4));//true


5.2 finding characters in a string

  1. Boolean contains (charsequences): returns true if and only if the string contains the specified char value sequence
  2. int indexOf(String str): returns the index where the specified substring first appears in this string
  3. int indexOf(String str, int fromIndex): returns the index where the specified substring first appears in this string, starting from the specified index
  4. int lastIndexOf(String str): returns the index of the specified substring at the rightmost position in the string
  5. int lastIndexOf(String str, int fromIndex): returns the index of the last occurrence of the specified substring in this string, starting from the specified index to start the reverse search

Note: both indexOf and lastIndexOf methods return - 1 if not found

Code example:

public void test3() {
    String s2="hello word";
    System.out.println(s2.indexOf("o", 5));//7
    System.out.println(s2.lastIndexOf("l", 2));//2

5.3 string operation method

  1. Replacement:

    • String replace(char oldChar, char newChar): returns a new string, which is obtained by replacing the oldChar in the string with newChar.
    • String replace(CharSequence target, CharSequence replacement): use the specified literal replacement sequence to replace the substring of the literal target sequence matched by this string.
    • String replaceAll(String regex, String replacement): replace the substring of the given regular expression with the given replacement.
    • String replaceFirst(String regex, String replacement): replace the string with the given replacement to match the first substring of the given regular expression.
  2. Match:

    • boolean matches(String regex): tells whether the string matches the given regular expression.
  3. section:

    • String[] split(String regex): splits the string based on the match of the given regular expression.

    • String[] split(String regex, int limit): split this string according to the given regular expression matching. The maximum number is no more than limit. If it is exceeded, all the rest will be put in the last element.

Code example:

public void test4() {
    String str1 = "Hello, Beijing";
    String str2 = str1.replace('north', 'south');

    System.out.println(str1);//Hello, Beijing
    System.out.println(str2);//Hello, Nanjing

    String str3 = str1.replace("Beijing", "Shanghai");
    System.out.println(str3);//Hello, Shanghai

    String str = "12hello34world5java7891mysql456";
    //Replace the number in the string with,, if there is one at the beginning and end of the result, remove it
    String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", "");

    str = "12345";
    //Determine whether all str strings are composed of numbers, that is, 1-n numbers
    boolean matches = str.matches("\\d+");
    String tel = "0571-4534289";
    //Determine if this is a fixed line phone in Hangzhou
    boolean result = tel.matches("0571-\\d{7,8}");

    str = "hello|world|java";
    String[] strs = str.split("\\|");
    for (int i = 0; i < strs.length; i++) {
        System.out.println(strs[i]);//Output hello word java in sequence
    str2 = "";
    String[] strs2 = str2.split("\\.");
    for (int i = 0; i < strs2.length; i++) {
        System.out.println(strs2[i]);//Output hello word java in sequence

6. Conversion between string and other structures

6.1 conversion between string, basic data type and packing class

String -- > basic data type, wrapper class: call the static method of wrapper class: parseXxx(str) basic data type, wrapper class -- > string: call the string overloaded valueOf(xxx)

Code example:

public void StringToBasic() {
    String str1 = "123";
    int i = Integer.parseInt(str1);
    System.out.println(i == 123);//true

    int j = 456;
    String s = String.valueOf(j);

6.2 conversion to character array

String -- > char []: calling tochararray() char [] -- > string of string: calling constructor of string

Code example:

public void BasicToString() {
    String s1 = "helloword";
    char[] chars = s1.toCharArray();
    for (int i = 0; i < chars.length; i++) {

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


6.3 conversion to byte array

Encoding: String -- > byte []: calling getBytes() of string decoding: byte [] -- > string: calling constructor of string

Encoding: String -- > byte (understandable -- > incomprehensible binary data) decoding: the reverse process of encoding, byte -- > string (incomprehensible binary data -- > understandable)

Note: when decoding, the character set required for decoding must be the same as the character set used for encoding, otherwise garbled code will appear.

public void StringToByteTest() throws UnsupportedEncodingException {
    String s1 ="Hello java world";
    byte[] bytesArray = s1.getBytes();//Use default character set encoding
    System.out.println(Arrays.toString(bytesArray));//[-28, -67, -96, -27, -91, -67, 106, 97, 118, 97, -28, -72, -106, -25, -107, -116]

    byte[] gbks = s1.getBytes("gbk");//Using gbk to encode sets
    System.out.println(Arrays.toString(gbks));//[-60, -29, -70, -61, 106, 97, 118, 97, -54, -64, -67, -25]


    String str1=new String(bytesArray);//Decode with default characters
    System.out.println(str1);//Hello java World

    String str2 = new String(gbks);//Decoding gbk encoding with default characters
    System.out.println(str2);//java decoding error, Chinese code scrambling, reason: coding and decoding are inconsistent

    String str3 = new String(gbks,"gbk");//Decoding in gbk format
    System.out.println(str3);//Hello java world, decoding is correct, reason: coding and decoding are consistent

6.4 conversion with StringBuffer and StringBuilder

1. String -- > StringBuffer, StringBuilder: call StringBuffer, StringBuilder builder builder

public void StringToStringBufferTest(){
    String str1 ="helloword";

    StringBuffer stringBuffer = new StringBuffer(str1);

    StringBuilder stringBuilder = new StringBuilder(str1);



2.StringBuffer, StringBuilder -- > String: ① call String builder; ② toString() of StringBuffer and StringBuilder

public void StringBuiderOrStringBufferToStringTest() {
    StringBuffer sb1 = new StringBuffer("hello StringBuffer");

    StringBuilder sb2 = new StringBuilder("hello StringBuider");


    String str1 = new String(sb1);

    String str2 = new String(sb2);


7. Description of storage location of string constant pool in JVM:

JDK 1.6 (JDK 6.0, Java 6.0): the string constant pool is stored in the method area (permanent area)

jdk 1.7: string constant pool stored in heap space

jdk 1.8: string constant pool stored in method area (meta space)

8. Examination of common algorithm problems:

1) Simulate a trim method to remove spaces at both ends of the string.

public String myTrim(String str) {
    if (str != null) {
        int start = 0;//Record the position index where the index position is not a space for the first time from the front to the back
        int end = str.length() - 1;//Record the first index position from the back to the front is not a space position index
        while (start < end && str.charAt(start) == ' ') {
        while (start < end && str.charAt(end) == ' ') {
        if (str.charAt(start) == ' ') {
            return "";
        return str.substring(start, end + 1);

    return null;

2) Inverts a string. Reverses the specified part of the string. For example, "abcdefg" is reversed to "abfedcg"

//Mode 1
public String reverse1(String str, int start, int end) {
    if (str != null) {
        //1. Convert to char array
        char[] charArray = str.toCharArray();
        //2. Reverse operation
        for (int i = start, j = end; i < j; i++, j--) {
            char temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
        //3. Return value
        return new String(charArray);
    return null;

//Mode 2
//Analysis: the whole string is divided into three parts: non reversed, reversed and non reversed
//First take out the front part that does not reverse, take out the reverse part, and then splice
public String reverse2(String string, int start, int end) {
    if(string != null){
        //Part I
    String newStr = string.substring(0, start);
    //Part II
    for (int i = end; i >= start; i--) {
        newStr += string.charAt(i);
    //Part III
    newStr += string.substring(end + 1);
	//Splicing operation
    return newStr;
    return null;

//Method 3: replace String optimization with StringBuffer or StringBuilder
public String reverse3(String str, int start, int end) {
    if(str != null){
      //1. Create a new StringBuffer
    StringBuffer stringBuffer = new StringBuffer(str.length());
    //2. Part I
    stringBuffer.append(str.substring(0, start));
    //3. Part II
    for (int i = end; i >= start; i--) {
    //4. Part III
    stringBuffer.append(str.substring(end + 1));
    //5. Splicing operation
    return stringBuffer.toString();  
    return null;

3) Gets the number of times a string appears in another string. For example, get the number of times "ab" appears in "abkkadkabkebfkabkskab"

public int count(String mainStr, String subStr) {
    //1. Judge the size of main string and partial string
    if (mainStr.length() >= subStr.length()) {
        int index = 0;
        int count = 0;
        //2. Take out the substring subscript in the main string, and assign the new subscript to the main string, and add 1 to the statistics
        //            while ((index = mainStr.indexOf(subStr) )!= -1){
        //                count++;
        //				//From the next substring found
        //                mainStr = mainStr.substring(index + subStr.length());
        //            }
        //No more new strings, only position comparison
        while ((index = mainStr.indexOf(subStr, index)) != -1) {
            index += subStr.length();
        return count;
    } else {
        return 0;

4) Gets the largest identical substring in two strings. For example: STR1 = "abcwertheloyiodef"; str2 = "cvhellobnm" prompt: compare the short string with the one with the decreasing length and the longer string.

//When there is only one substring
public String getMaxSameSubString(String str1, String str2) {
    //1. Determine the size of two strings
    if (str1 != null && str2 != null) {
        String maxStr = (str1.length() >= str2.length()) ? str1 : str2;
        String minStr = (str1.length() < str2.length()) ? str1 : str2;

        int len = minStr.length();
        //2. Use the small ones to compare the large ones in turn
        for (int i = 0; i < len; i++) {//This layer of for loop is used to determine the number of characters to be compared
            for (int x = 0, y = len - i; y <= len; x++, y++) {
                if (maxStr.contains(minStr.substring(x, y))) {
                    return minStr.substring(x, y);

    return null;

//In the case of multiple identical substrings
// At this time, return String [] first, and then replace it with ArrayList in the collection, which is more convenient
public String [] getMaxSameSubStrings(String str1, String str2) {
    //1. Compare the size of two substrings first
    if (str1 != null && str2 != null) {
        StringBuffer stringBuffer = new StringBuffer();
        String maxStr = (str1.length() > str2.length()) ? str1 : str2;
        String minStr = (str1.length() > str2.length()) ? str2 : str1;
        //2. Match the big one with the small one
        int len = minStr.length();
        for (int i = 0; i < len; i++) {
            for (int x = 0, y = len - i; y <= len; x++,y++ ){
                String subString = minStr.substring(x,y);
                //3. Take out the matched substring
                if (maxStr.contains(subString)){
            if (stringBuffer.length() != 0){

        String [] split = stringBuffer.toString().replaceAll(",$","").split("\\,");
        return split;
    return null;

5) Sort the characters in a string in natural order. Tips:

  1. The string becomes an array of characters.

  2. Sort array, select, bubble, Arrays.sort();

  3. Turn the sorted array into a string.

public void charTest() {
    String str1 = "hello java";
    char[] charArray = str1.toCharArray();


    String str2 = new String(charArray);

2, StringBuffer and StringBuilder

(1) StringBuffer class

1. Overview:

java.lang.String.Buffer represents a variable character sequence. It is declared in JDK 1.0 that the String content can be added or deleted, and no new objects will be generated at this time. When many methods are passed as parameters like String, the value can be changed inside the method.

abstract class AbstractStringBuilder implements Appendable, CharSequence {
     * The value is used for character storage.
    char[] value;//value has no final declaration. value can continue to expand

     * The count is the number of characters used.
    int count;//count records the number of valid characters

The StringBuffer class is different from String, and its objects must be generated using a constructor.

There are three constructors StringBuffer(): a string buffer with an initial capacity of 16

StringBuffer(int size): construct a string buffer of specified capacity

StringBuffer(String str): initializes the content to the specified string content

String s= new String("I like learning");
StringBuffer buffer= new StringBuffer("I like learning");
buffer. append("Mathematics");

2. Common methods:

  1. StringBuffer append(xxx): many append() methods are provided for string splicing
  2. StringBuffer delete(int start,int end): delete the content at the specified location
  3. StringBuffer replace(int start, int end, String str): replace the [start,end) position with str
  4. StringBuffer insert(int offset, xxx): insert xxx at the specified location
  5. StringBuffer reverse(): reverses the current character sequence

When append and insert, if the original queue array is not long enough, it can be expanded. These methods support method chain operations. Principle of method chain:

public StringBuilder append(String str) {
    return this;
  • public int indexOf(String str): returns the subscript of the substring
  • public String substring(int start,int end): returns a substring of left closed right open interval from start to end index
  • public int length(): get the length of the string
  • public char charAt(int n): returns a character at a specified location
  • Public void setcharat (int n, char CH): set the character of the specified position


Add: append(xxx);

delete(int start,int end);

Change: setcharat (int n, char CH) / replace (int start, int end, string STR);

charAt(int n);

insert(int offset, xxx);

Length: length();

*Traversal: for() + charAt() / toString();

Code example:

public void stringBufferMethodTest(){
    StringBuffer s1 = new StringBuffer("abc");

    System.out.println(s1.delete(0, 1));//bc1
    System.out.println(s1.replace(0, 1, "hello"));//helloc1
    System.out.println(s1.insert(3, "v"));//helvloc1

(2) StringBuilder class

StringBuilder and StringBuffer are very similar, both represent variable character sequences, and the methods to provide related functions are the same. However, StringBuilder class does not have thread lock, so the execution efficiency is higher.

1. Comparison of string, StringBuffer and StringBuilder

  • String: immutable character sequence; the bottom layer uses char [] to store; takes up memory (constantly creating and recycling objects)
  • StringBuffer: variable character sequence; thread safe, low efficiency; thread safe; bottom layer uses char [] storage;
  • StringBuilder: variable character sequence; jdk5.0 new, thread unsafe, high efficiency; thread unsafe; bottom layer uses char [] storage

Note: if passed as a parameter, Stng in the method will not change its value, StringBuffer and StringBuilder will change its value.

2. Memory resolution of StringBuffer and StringBuilder

Take StringBuffer as an example:

String str = new String();//char[] value = new char[0];
String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};

StringBuffer sb1 = new StringBuffer();//char[] value = new char[16]; the underlying creates an array of length 16.
sb1.append('a');//value[0] = 'a';
sb1.append('b');//value[1] = 'b';

StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];

StringBuffer constructor source code:

public StringBuffer(String str) {
    super(str.length() + 16);

Question 1. System.out.println(sb2.length());//3

Problem 2. Capacity expansion: if the underlying array of data to be added can't hold, you need to expand the underlying array. By default, the capacity is expanded to 2 times + 2 of the original capacity, and the elements in the original array are copied to the new array.

Guiding significance: it is recommended to use StringBuffer(int capacity) or StringBuilder(int capacity) in development

3. Compare the execution efficiency of String, StringBuffer and StringBuilder

From high to low: StringBuilder > StringBuffer > string

public void test3(){
    //Initial settings
    long startTime = 0L;
    long endTime = 0L;
    String text = "";
    StringBuffer buffer = new StringBuffer("");
    StringBuilder builder = new StringBuilder("");
    //Start to compare
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 20000; i++) {
    endTime = System.currentTimeMillis();
    System.out.println("StringBuffer Execution time of:" + (endTime - startTime));

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 20000; i++) {
    endTime = System.currentTimeMillis();
    System.out.println("StringBuilder Execution time of:" + (endTime - startTime));

    startTime = System.currentTimeMillis();
    for (int i = 0; i < 20000; i++) {
        text = text + i;
    endTime = System.currentTimeMillis();
    System.out.println("String Execution time of:" + (endTime - startTime));


3, Date time API before JDK 8.0

1. java.lang.System class

The public static long currentTimeMillis() provided by the System class is used to return the time difference in milliseconds between the current time and 0:00:00 on January 1, 1970. (time stamp) this method is suitable for calculating time difference.

The main criteria for calculating world time are:

UTC(Coordinated Universal Time) GMT(Greenwich Mean Time) CST(Central Standard Time)

Code example:

//Get the current time of the System: currentTimeMillis() in the System class
long time = System.currentTimeMillis();
//Returns the time difference in milliseconds between the current time and 0:00:00, January 1, 1970.
//Called a timestamp

2. java.util.Date class

Represents a specific instant, accurate to milliseconds

2.1 constructor

Date(): create an object with a constructor without parameters to get the local current time

Date(long date)

2.2 common methods

getTime(): returns the number of milliseconds represented by this Date object since January 1, 1970, 00:00:00 GMT

tostring(): converts this Date object to a String of the following form:

  • dow mon dd
  • hh: mm:ss zzz yyyy

Where: doW is one day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat), zzz is the time standard. Many other methods are out of date

2.3java.util.Date class and java.sql.Date class

java.util.Date class

|---java.sql.Date class

1. Use of two constructors

>Constructor 1: Date(): create a Date object corresponding to the current time

>Constructor 2: creates a Date object with a specified number of milliseconds

2. Use of two methods

>Tostring(): display the current year, month, day, hour, minute and second

>Gettime(): gets the number of milliseconds corresponding to the current Date object. (time stamp) corresponds to the date type variable in the database

How to instantiate

How to convert java.util.Date object to java.sql.Date object

public void dateTest(){
    //Constructor 1: Date(): create a Date object corresponding to the current time
    Date date1 = new Date();
    System.out.println(date1.toString());//Sun Apr 19 13:35:12 CST 2020

    //Constructor 2: creates a Date object with a specified number of milliseconds
    Date date2 = new Date(15872745176L);

    //Create java.sql.Date object
    java.sql.Date date3 = new java.sql.Date(1587274512876L);

    //How to convert java.util.Date object to java.sql.Date object
    Date date4 = new Date();
    //First, there is a problem: java.util.Date cannot be cast to java.sql.Date
    //        java.sql.Date date6 = (java.sql.Date) date4;
    //        System.out.println(date6);
    //The second way
    java.sql.Date date5 = new java.sql.Date(date4.getTime());

3. java.text.SimpleDateFormat class

The AP of the Date class is not easy to internationalize, and most of it is abandoned. The java.text.SimpleDateFormat class is a concrete class that does not relate to the language environment to format and parse dates.

It allows formatting: date → text, parsing: text → date

● format:

SimpleDateFormat(): default schema and locale creation object

public SimpleDateFormat(String pattern): this construction method can create an object in the format specified by the parameter pattern. The object calls:

Public string format (date date): method format time object date

● parsing: public Date parse(String source): parsing text from the beginning of a given string to generate dates

1. Format and resolution of simpledateformat to Date class

Two operations:

1.1 format: date -- > string

1.2 parsing: the inverse process of formatting, string -- > date

2. Instantiation of simpledateformat: new + constructor

Format and parse as specified: call constructor with parameters

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");

Code example:

public void test2() throws ParseException {
    //Instantiate Date object
    Date date1 = new Date();
    //Instantiate the simpledateformat object and format the display
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:aaa");
    //Format date object
    String format = simpleDateFormat.format(date1);
    System.out.println(format.toString());//2020-09-19 02:09: PM
    //Parsing: it is required that the string must be in a format recognized by SimpleDateFormat (embodied by constructor parameters),
    //Otherwise, throw the exception
    Date date2 = simpleDateFormat.parse("2020-04-20 14:20:Afternoon");
    System.out.println(date2.toString());//Tue Jan 21 02:20:00 CST 2020

Small exercises:

Exercise 1: convert the string "2020-09-08" to java.sql.Date

public void test3() throws ParseException {
    String brith = "1997-10-15";
    //Create a new SimpleDateFormat object and format the time
    SimpleDateFormat simpBrith = new SimpleDateFormat("yyyy-mm-dd");
    //Format time in string format as Date class
    Date brithday = simpBrith.parse(brith);
    //Through the getTime method of Date, the Date object is transformed into a time stamp and put into the constructor of class
    java.sql.Date brithDate = new java.sql.Date(brithday.getTime());

4. Calendar Class: calendar class, abstract class

Calendar is an abstract base class, which is mainly used to complete the interaction between date fields.

  • The method that gets the calendar instance uses the Calendar.getInstance() method to call the constructor of its subclass, GregorianCalendarl.
  • An instance of Calendar is an abstract representation of system time, which is obtained by get(int field) method. For example, YEAR, MONTH, day of week, hour of day, MINUTE, second public void set (int field, int value) public void add (int field, int amount) public final date get time() public final void set time (date date date)
  • Pay attention to getting month: January is 0, February is 1, and so on. December is 11. Get week: Sunday is 1, Tuesday is 2,... Saturday is 7

4.1 instantiation

Method 1: create the object of its subclass (Gregorian calendar)

Method 2: call its static method getInstance()

Calendar calendar = Calendar.getInstance();

4.2 common methods

get(): get date

set(): set date

add(): date of adding and modifying

getTime: Calendar Class -- > date

SetTime: date -- > Calendar Class

Code example:

Calendar calendar = Calendar.getInstance();
//        System.out.println(calendar.getClass());

//2. Common methods
int days = calendar.get(Calendar.DAY_OF_MONTH);//Get the day of the month
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//Get the day of the year

//calendar variability
calendar.set(Calendar.DAY_OF_MONTH,22);//Set day of the month
days = calendar.get(Calendar.DAY_OF_MONTH);

days = calendar.get(Calendar.DAY_OF_MONTH);

//getTime(): Calendar Class -- > date
Date date = calendar.getTime();

//Settime(): date -- > Calendar Class
Date date1 = new Date();
days = calendar.get(Calendar.DAY_OF_MONTH);

4, New date time class in JDK 8.0

1. Iteration of date time API:

First generation: jdk 1.0 Date class

The second generation: jdk 1.1 Calendar class, replacing Date class to some extent

The third generation: jdk 1.8 puts forward a new set of API

2. Problems of the first two generations:

Variability: classes like date and time should be immutable.

Offset: the year in Date starts from 1900, and the months start from 0.

Format: format is only used for Date, not Calendar. In addition, they are not thread safe; they cannot handle leap seconds, etc.

java.time API introduced in Java 8.0:

Java 8 absorbs the essence of Joda-Time and creates a good APl for Java with a new start. The new java.time contains all classes about local Date, local time, local Date time, zonedate time, and duration. The old Date class added the tolnstant() method to convert a Date into a new representation. These new localized time Date API s greatly simplify the management of Date time and localization.

3. Packages involved in the new date time API in Java 8.0:

4. Use of local date, local time and local date time:

LocalDate / LocalTime / LocalDateTime

4.1 Description:

① Represents the date, time, date, and time using the ISO-8601 Calendar system, respectively. They provide a simple local date or time and do not contain current time information or time zone related information. ② Compared with LocalDate and LocalTime, the use frequency of LocalDateTime is higher ③ similar to Calendar

4.2 common methods:

Code example:

public void test1(){
    //now(): get the current date, time, datetime
    LocalDate localDate =;
    LocalTime localTime =;
    LocalDateTime localDateTime =;


    //of(): set the specified year, month, day, hour, minute and second. No offset
    LocalDateTime localDateTime1 = LocalDateTime.of(2020,10,6,12,13,12);

    //getXxx(): get related properties

    //Reflect immutability
    //withXxx(): set related properties
    LocalDate localDate1 = localDate.withDayOfMonth(22);

    LocalDateTime localDateTime2 = localDateTime.withHour(4);

    LocalDateTime localDateTime3 = localDateTime.plusMonths(3);

    LocalDateTime localDateTime4 = localDateTime.minusDays(6);

5. Time point: Instant

5.1 Description:

① An instantaneous point on the time line. Conceptually, it's just a simple representation of the number of seconds since January 1, 1970, at 0:00:00

② Similar to the java.util.Date class

5.2 common methods:

Code example:

public void test2(){
    //now(): get the standard time corresponding to the prime meridian
    Instant instant =;

    //Add time offset
    OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));

    //toEpochMilli(): get the number of milliseconds from 0:00:00:00 (UTC) on January 1, 1970 -- > getTime() of the date class
    long milli = instant.toEpochMilli();

    //ofEpochMilli(): get the Instant instance by the given number of milliseconds -- > date (long millis)
    Instant instant1 = Instant.ofEpochMilli(1587467105795L);

6. Date time format class: DateTimeFormatter

6.1 Description:

① Format or parse date and time

② Similar to SimpleDateFormat

6.2 common methods:

  1. Instantiation method: predefined standard format. For example, the formats related to ISO ﹣ local ﹣ date; time. For example: ofLocalizedDateTime(FormatStyle.LONG) custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")

  2. Common methods:

    Special: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")

    Code example:

    public void test3(){
        //        Mode 1: predefined standard format.
        //        For example: ISO "local" date "time; ISO" local "date; ISO" local "time
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //Format: date -- > string
        LocalDateTime localDateTime =;
        String str1 = formatter.format(localDateTime);
        //Parsing: String -- > date
        TemporalAccessor parse = formatter.parse("2000-04-21T19:13:13.53");
        System.out.println(parse);//{},ISO resolved to 2000-04-21T19:13:13.530
        //        Mode 2:
        //        Localization related formats. For example: ofLocalizedDateTime()
        //        Formatstyle.long/formatstyle.medium/formatstyle.short: applicable to LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//April 21, 2020 07:16:57 PM
        //      Localization related formats. For example: ofLocalizedDate()
        //      Formatstyle.full/formatstyle.long/formatstyle.medium/formatstyle.short: applicable to LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        String str3 = formatter2.format(;
        //       Key point: method three: custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String Str4 = formatter3.format(;
        System.out.println(Str4);//2020-04-21 07:24:04
        TemporalAccessor accessor = formatter3.parse("2020-02-03 05:23:06");
        System.out.println(accessor);//{SecondOfMinute=6, HourOfAmPm=5, NanoOfSecond=0, MicroOfSecond=0, MinuteOfHour=23, MilliOfSecond=0},ISO resolved to 2020-02-03

7. Use of other API s:

7.1 date time with time zone:

ZonedDateTime / ZoneId

Code example:

// ZoneId: the class contains the time zone information
public void test1(){
    //Getavailablezones(): get the ZoneId
    Set<String> zoneIds = ZoneId.getAvailableZoneIds();
    for(String s : zoneIds){

    //Get the time corresponding to "Asia/Tokyo" time zone
    LocalDateTime localDateTime ="Asia/Tokyo"));

//ZonedDateTime: date time with time zone
public void test2(){
    //now(): get the zonedatetime object of this time zone
    ZonedDateTime zonedDateTime =;
    //Now (zoneid): gets the zonedatetime object of the specified time zone
    ZonedDateTime zonedDateTime1 ="Asia/Tokyo"));

7.2 time interval:

Duration -- used to calculate two "time" intervals, based on seconds and nanoseconds

Code example:

public void test3(){
    LocalTime localTime =;
    LocalTime localTime1 = LocalTime.of(15, 23, 32);
    //between(): static method, return the Duration object, representing the interval between two times
    Duration duration = Duration.between(localTime1, localTime);


    LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32);
    LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32);

    Duration duration1 = Duration.between(localDateTime1, localDateTime);


7.3 date interval:

Period -- used to calculate two "date" intervals, measured by year, month, and day

Code example:

public void test4(){
    LocalDate localDate =;
    LocalDate localDate1 = LocalDate.of(2028, 3, 18);

    Period period = Period.between(localDate, localDate1);


    Period period1 = period.withYears(2);


7.4 date time corrector: TemporalAdjuster

Code example:

public void test5(){
    //What is the next Sunday to get the current date?
    TemporalAdjuster temporalAdjuster =;

    LocalDateTime localDateTime =;

    //What is the next working day?
    LocalDate localDate = TemporalAdjuster(){

        public Temporal adjustInto(Temporal temporal) {
            LocalDate date = (LocalDate)temporal;
                return date.plusDays(3);
            }else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){
                return date.plusDays(2);
                return date.plusDays(1);



    System.out.println("The next working day is:" + localDate);

7.5 transformation between new date API and original API:

5, Java comparator

1. Background of Java comparator:

  • Under normal circumstances, objects in Java can only be compared: = = or! =. Cannot use > or < of
  • But in the development scenario, we need to sort multiple objects, and then we need to compare the size of the objects.
  • How to achieve it? Use either of two interfaces: Comparable or custom

2. Natural sorting: use the compatible interface

2.1 description

  1. For example, String and wrapper class implement the Comparable interface, rewrite the compareTo(obj) method, and give a way to compare the size of two objects.

  2. After overriding the compareTo() method like String and wrapper class, they are arranged from small to large

  3. Rewrite the rule of compareTo(obj): if the current object this is greater than the parameter object obj, a positive integer is returned; if the current object this is less than the parameter object obj, a negative integer is returned; if the current object this is equal to the parameter object obj, a zero is returned.

  4. For custom classes, if sorting is needed, we can let the custom class implement the compatible interface and override the compareTo(obj) method. Indicate how to sort in compareTo(obj) method

  5. Typical implementation of compatable: (the default is arranged from small to large) String: compare by the Uincode value of the characters in the String Character: compare by the Unicode value of the characters the wrapper class corresponding to the numerical type and BigInteger, BigDecimal: compare by the corresponding numerical size Boolean: the package instance corresponding to true is greater than the package instance corresponding to false Date, Time, etc.: the later Date Time is greater than the earlier Date Time

2.2 example of custom code:

public class Goods implements  Comparable{

    private String name;
    private double price;

    //How to specify the size of commodity comparison: sort by price from low to high, and then sort by product name from high to low
    public int compareTo(Object o) {
        //        System.out.println("**************");
        if(o instanceof Goods){
            Goods goods = (Goods)o;
            //Mode 1:
            if(this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
                //                return 0;
            //Mode 2:
            //           return,goods.price);
        //        return 0;
        throw new RuntimeException("Incoming data type is inconsistent!");
    // getter, setter, toString(), constructor: omitted

3. Custom sorting: using the Comparator interface

3.1 Description:

  1. Background:

When the type of the element does not implement the java.lang.Comparable interface and it is not convenient to modify the code, or the sorting rules that implement the java.lang.Comparable interface are not suitable for the current operation, then you can consider using the object of the Comparator to sort

2. Rewrite the compare(Object o1,Object o2) method to compare the size of o1 and o2:

If the method returns a positive integer, o1 is greater than o2;

If 0 is returned, it means equal;

Returns a negative integer indicating that o1 is less than o2.

3.2 code example:

Comparator com = new Comparator() {
    //Indicate how items are compared in size: sorted by product name from low to high, and then by price from high to low
    public int compare(Object o1, Object o2) {
        if(o1 instanceof Goods && o2 instanceof Goods){
            Goods g1 = (Goods)o1;
            Goods g2 = (Goods)o2;
                return g1.getName().compareTo(g2.getName());
        throw new RuntimeException("Inconsistent data type entered");

4. Comparison of two sorting methods

  • The way of the compatible interface is certain to ensure that the objects of the compatible interface implementation class can be compared in any position.
  • The Comparator interface is a temporary comparison.

6, Other common classes

1.System class

  • The System class represents the System, and many System level properties and control methods are placed inside the class. This class is located in the java.lang package.
  • Because the constructor of this class is private, the object of this class cannot be created, that is, the class cannot be instantiated. Its internal member variables and member methods are static, so it is convenient to call.

Member method:

  • native long currentTimeMillis():

    The function of this method is to return the current computer time. The expression of time is the number of milliseconds between the current computer time and GMT time (Greenwich mean time) on January 1, 1970 at 0:00:00.

  • void exit(int status)

    The function of this method is to exit the program. The value of status is 0 for normal exit and non-zero for abnormal exit. With this method, the program exit function can be realized in GUI programming

  • void gc()

    The function of this method is to request the system for garbage collection. As for whether the system can recover immediately depends on the implementation of garbage collection algorithm and the execution of the system.

  • String getProperty(String key)

    The function of this method is to get the corresponding value of the attribute named key in the system. The common attribute names and functions in the system are shown in the following table:

Code example:

public void test1() {
    String javaVersion = System.getProperty("java.version");
    System.out.println("java Of version:" + javaVersion);

    String javaHome = System.getProperty("java.home");
    System.out.println("java Of home:" + javaHome);

    String osName = System.getProperty("");
    System.out.println("os Of name:" + osName);

    String osVersion = System.getProperty("os.version");
    System.out.println("os Of version:" + osVersion);

    String userName = System.getProperty("");
    System.out.println("user Of name:" + userName);

    String userHome = System.getProperty("user.home");
    System.out.println("user Of home:" + userHome);

    String userDir = System.getProperty("user.dir");
    System.out.println("user Of dir:" + userDir);


2.Math class

java.lang.Math provides a series of static methods for scientific calculation. The parameter and return value types of the method are generally double type.

3.BigInteger class, BigDecimal class


BigInteger of java.math package can represent immutable integer with arbitrary precision.

BigInteger provides the corresponding objects of all basic integer operators in Java, and provides all related methods of java.lang.Math. In addition, BigInteger provides the following operations: modular arithmetic, GCD calculation, prime number test, prime number generation, bit operation, and some other operations.

Constructor: BigInteger(String val): build BigInteger object based on string

Code example:

public void test2() {
    BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
    BigDecimal bd = new BigDecimal("12435.351");
    BigDecimal bd2 = new BigDecimal("11");
    //         System.out.println(bd.divide(bd2));
    System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
    System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));


3.2 BigDecimal

It requires high digital precision, using java.math.BigDecimal class

The BigDecimal class supports immutable, arbitrary precision signed decimal number of specified points.

● constructor

public BigDecimal(double val)

public BigDecimal(String val)

● common methods

public BigDecimal add(BigDecimal augend)

public BigDecimal subtract(BigDecimal subtrahend)

public BigDecimal multiply(BigDecimal multiplicand)

public BigDecimal divide(BigDecimal divisor, int scale, int rounding Mode)

Code example:

public void test2() {
    BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
    BigDecimal bd = new BigDecimal("12435.351");
    BigDecimal bd2 = new BigDecimal("11");
    //         System.out.println(bd.divide(bd2));
    System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
    System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));


Topics: Programming Java SQL JavaEE JDK