Java foundation - common classes

1. String class

Characteristics of String class

  • String is declared final, which means it cannot be inherited
  • final char[] value is defined inside String to store String data
  • String represents an immutable character sequence (immutable)
  • String implements the Serializable interface: it means that the string supports serialization. (Serializable: can be output by output stream)
  • String implements the Comparable interface: it means that string can compare sizes

Immutability

  • When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment.
  • When connecting an existing string, you also need to assign a value to the memory area again. The original value cannot be used for assignment.
  • When calling the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment, and the original value cannot be used for assignment.

How String objects are created

  1. Literal quantity method: String S1 = "ABC"; (stored in constant pool)
  2. New + constructor mode: String S2 = new string ("ABC"); (stored in heap)
//Literal expression
String str = "hello";

//Essentially this value = new char[0];
String  s1 = new String(); 

//this.value = original.value;
String  s2 = new String(String original); 

//this.value = Arrays.copyOf(value, value.length);
String  s3 = new String(char[] a);

String  s4 = new String(char[] a,int startIndex,int count);

What is the difference between String str1 = "abc" and String str2 = new String("abc")?

  • String constants are stored in the string constant pool for sharing
  • String non constant objects are stored in the heap.

The difference between String class splicing

  • The splicing results of constants and constants are in the constant pool, and the same constants will not appear in the constant pool
  • As long as one of the splice members is a variable, the result is in the heap
  • If the splicing result calls intern (), the return value is in the constant pool
public class Stringtest {
    public static void main(String[] args){

        String s1="A"; //Constant pool
        String s2="B"; //Constant pool
        String s3="AB"; //Constant pool
        String s4="A"+"B"; //Constant pool
        String s5="A"+s2; //heap
        String s6=s1+s2; //heap

        System.out.println(s1+s2==s4);//f
        System.out.println(s1+s2 ==s3);//f
        //Special attention!!!
        //"A" is a constant and s1 is a variable
        
        System.out.println(s3==s4);//t
        System.out.println(s3==s5);//f
        System.out.println(s3==s6);//f
        System.out.println(s5==s6);//f, also in the heap but with different addresses
        System.out.println(s4==s6);//f
        
        System.out.println(s6.intern() == s3);//t
    }
}



Common methods of String 1

  • int length(): returns the length of the string
  • char charAt(int index): returns the character at an index
  • boolean isEmpty(): judge whether it is an empty string
  • String toLowerCase(): converts all characters in a string to lowercase using the default locale
  • String toUpperCase(): converts all characters in a string to uppercase using the default locale
  • String trim(): returns a copy of a string, ignoring leading and trailing whitespace
  • boolean equals(Object obj): compare whether the contents of strings are the same
  • Boolean equalsignorecase (string otherstring): similar to the equals method, case is ignored
  • String concat(String str): concatenates the specified string to the end of this string. Equivalent to "+"
  • Int CompareTo (string otherstring): compares the size of two strings
  • String substring(int beginIndex): returns a new string, which is the last substring of the string intercepted from beginIndex.
  • String substring(int beginIndex,int endIndex): returns a new string, which is a substring intercepted from beginIndex to endindex (excluding).
public class StringWay1 {
    public static void main(String[] args){
        String s1="ABCabc";
        String s2="";
        String s3="  ABC   A";
        String s4="ABCABC";

        //length()
        System.out.println(s1.length());

        //charAt(int index)
        System.out.println(s1.charAt(2));

        //isEmpty()
        System.out.println(s1.isEmpty());
        System.out.println(s2.isEmpty());

        //toLowerCase(), converts all characters in the String to lowercase
        System.out.println(s1.toLowerCase());

        //toUpperCase(), converts all characters in the String to uppercase
        System.out.println(s1.toUpperCase());

        //trim(): returns a copy of a string, ignoring leading and trailing whitespace
        System.out.println(s3.trim());

        //equals(Object obj): compare whether the contents of the string are the same
        System.out.println(s1.equals(s4));

        //Equalsignorecase (string otherstring): similar to the equals method, case is ignored
        System.out.println(s1.equalsIgnoreCase(s4));

        //String concat(String str): concatenates the specified string to the end of this string. Equivalent to "+"
        System.out.println(s1.concat("123"));

        //CompareTo (string another string): compares the size of two strings
        System.out.println(s1.compareTo(s4));

        //substring(int beginIndex): returns a new string, which is the last substring intercepted from beginIndex.
        System.out.println(s1.substring(2));

        //substring(int beginIndex,int endIndex): returns a new string, which is a substring intercepted from beginIndex to endindex (excluding).
        System.out.println(s1.substring(1,3));
        
    }
}

Common methods of String 2

  • boolean endsWith(String suffix): tests whether the string ends with the specified suffix
  • boolean startsWith(String prefix): tests whether this string starts with the specified prefix
  • Boolean startswith (string prefix, int tofffset): test whether the substring of this string starting from the specified index starts with the specified prefix
  • Boolean contains (charsequences): returns true if and only if this string contains the specified char value sequence
  • int indexOf(String str): returns the index of the first occurrence of the specified substring in this string
  • int indexOf(String str, int fromIndex): returns the index of the first occurrence of the specified substring in this string, starting from the specified index
  • int lastIndexOf(String str): returns the index of the rightmost occurrence of the specified substring in this string
  • int lastIndexOf(String str, int fromIndex): returns the index of the last occurrence of the specified substring in this string, and reverses the search from the specified index
public class StringWay2 {
    public static void main(String[] args){
        String s1="ABCabc";
        String s2="";
        String s3="  ABC   A";
        String s4="ABCABC";
        char[] arr=new char[]{'A','B'};

        //endsWith(String suffix): tests whether the string ends with the specified suffix
        System.out.println(s1.endsWith("abc"));
        System.out.println(s1.endsWith("ac"));

        //startsWith(String prefix): tests whether this string starts with the specified prefix
        System.out.println(s1.startsWith("A"));
        System.out.println(s2.startsWith(" "));

        //Startswith (string prefix, int tofffset): tests whether the substring of this string starting from the specified index starts with the specified prefix
        System.out.println(s1.startsWith("BC",1));

        // indexOf(String str): returns the index of the first occurrence of the specified substring in this string
        System.out.println(s4.indexOf("C"));
        System.out.println(s4.indexOf("D"));

        //int indexOf(String str, int fromIndex): returns the index of the first occurrence of the specified substring in this string, starting from the specified index
        System.out.println(s4.indexOf('A',1));

        // lastIndexOf(String str): returns the index of the rightmost occurrence of the specified substring in this string
        System.out.println(s4.lastIndexOf('C'));

        //lastIndexOf(String str, int fromIndex): returns the index of the last occurrence of the specified substring in this string, and reverses the search from the specified index
        System.out.println(s4.lastIndexOf('C',4));
        
    }
}

Common methods of String 3

  • replace
  • String replace(char oldChar, char newChar): returns a new string obtained by replacing all oldchars appearing in this string with newChar.
  • String replace(CharSequence target, CharSequence replacement): replaces all substrings of this string that match the literal target sequence with the specified literal replacement sequence.
  • String replaceAll(String regex, String replacement): replace all substrings of this string that match the given regular expression with the given replacement.
  • String replaceFirst(String regex, String replacement): replace this string with the given replacement to match the first substring of the given regular expression.
  • Match:
  • boolean matches(String regex): tells whether the string matches the given regular expression.
  • section:
  • String[] split(String regex): splits the string according to the matching of the given regular expression.
  • String[] split(String regex, int limit): split the string according to the matching given regular expression. The maximum number is no more than limit. If it exceeds the limit, all the rest will be placed in the last element.

Conversion between String and char []

  • String -- "char []: call string's toCharArray()
  • char [] - String: constructor calling string
public void test1(){
        //String ->  char[]

        String s1="ABCaad";
        char[] s2= s1.toCharArray();

        for(char c :s2){
            System.out.println(c);
        }

        //char[] ->String
        String s3=new String(s2);
        System.out.println(s3);

    }

Conversion between String and bytes []

  • String - bytes []: call getBytes() of string
    • This process is encoding: String - binary data
  • bytes [] - String: call the constructor of string
    • This process is decoding: binary data - string
  • The encoding set and decoding set must be consistent (UTF-8 by default), otherwise garbled code will appear
public void test2(){

        //String -> byte[]
        //Encoding: String binary data
        String s1="abc123";
        byte[] s2=s1.getBytes();

        for(byte b:s2){
            System.out.println(b);
        }

        //byte[] -> String
        //Decoding: binary data - string
        String s3=new String(s2);

        System.out.println(s3);

    }

2. Stringbuffer and Stringbuilder

Similarities and differences among String, StringBuffer and StringBuilder

  • String: immutable character sequence; The bottom layer uses char [] storage
  • StringBuffer: variable character sequence; Thread safety and low efficiency; The bottom layer uses char [] storage
  • StringBuilder: variable character sequence; jdk5.0 new, thread unsafe, high efficiency; The bottom layer uses char [] storage

Stringbuffer source code analysis

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 bottom layer creates an array with a length of 16.
StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];
//Same as Stringbuilder

Capacity expansion problem

If the underlying array of data to be added is not enough, the underlying array needs to be expanded. 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. (automatic capacity expansion)
It is recommended that you use StringBuffer (int capacity) or StringBuilder (int capacity) to specify the creation of an object with capacity.

StringBuffer common methods

  • StringBuffer append(xxx): provides many append() methods for string splicing
  • StringBuffer delete(int start,int end): deletes the contents of the specified location
  • StringBuffer replace(int start, int end, String str): replace the [start,end) position with str
  • StringBuffer insert(int offset, xxx): inserts xxx at the specified position
  • StringBuffer reverse(): reverses the current character sequence
  • int indexOf(String str)
  • String substring(int start,int end): returns a substring of the left closed right open interval from start to end [start, end]
  • int length(): returns the length of the string
  • summary
    • Add: append(xxx)
    • Delete: delete(int start,int end)
    • Change: replace(int start, int end, String str)
    • Query: charAt(int n)
    • Insert: insert(int offset, xxx)
    • Length: length();
    • Traversal: for() + charAt() / toString()

Efficiency comparison of String, Stringbuffer and Stringbuilder

  • Arrange 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 comparison
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            buffer.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuffer Execution time of:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            builder.append(String.valueOf(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));

    }
}

5. Date class

Date class

  • java.util.Date class - > represents a specific moment, accurate to milliseconds
    • |—java.sql.Date class (subclass) (corresponding to the variable of date type in the database)
  • java. util. Instantiation of date class
    • Date(): create a date object corresponding to the current time
    • Date (long time): creates a date object with a specified number of milliseconds
  • java. sql. Instantiation of date class
    • Date (long time): creates a date object with a specified number of milliseconds
  • Two methods
    • toString(): displays the current year, month, day, hour, minute and second
    • getTime(): gets the number of milliseconds corresponding to the current Date object. (distance 1970-01-01)
      • Timestamp: milliseconds from 1970-01-01
public void test1(){
        //java. util. Instantiation of date()
        //1
        Date date1=new Date();
        //2
        Date date2=new Date(1516161615615L);

        System.out.println(date1.toString()+"   "+date1.getTime());
        System.out.println(date2.toString()+"   "+date1.getTime());

        //java. sql. Instantiation of date()
        java.sql.Date date3=new java.sql.Date(15615115161651L);

        System.out.println(date3.toString());
    }
  • Set util Convert Date object to SQL Data object
        //Mode 1: polymorphic strong transformation
        java.util.Date D1=new java.sql.Date(1561616616l);
        java.sql.Date  D2=(java.sql.Date)D1;

        System.out.println(D2.toString());

        //Method 2: call getTime()
        java.util.Date D3=new java.util.Date(1161651515L);
        java.sql.Date  D4=new java.sql.Date(D3.getTime());

        System.out.println(D4.toString());

SimpleDateFormat class

  • The API of Date class is not easy to internationalize, and most of them are abandoned, Java text. The simpledateformat class is a concrete class that formats and parses dates in a locale independent manner.
  • It allows
    • Format: date - > text
    • Parse: text - > date
public void test2() {
        Date date = new Date(1561161616L);

        //format
        //Date string
        SimpleDateFormat sdf = new SimpleDateFormat();
        String date1 = sdf.format(date);

        System.out.println(date);
        System.out.println(date1);

        //analysis
        //String - date
        //parse() requires try/catch
        try {
            Date date2 = sdf.parse(date1);//Format needs to be consistent
            System.out.println(date2.toString());

        } catch (ParseException e) {
            e.printStackTrace();
        }
   }

//Format and parse as specified: call the constructor with parameters
 public void test3() {
        Date date1 = new Date(1562615151561651L);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//Convert to a string in the form yyyy MM DD HH: mm: SS
        //format
        String date2 = sdf.format(date1);
        System.out.println(date2);


        try {
            Date date3 = sdf.parse(date2);
            System.out.println(date3);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//
//        Date date4=new Date(165165161L);
//        System.out.println(date4);
    }
//Examples
//The string "2020-09-08" is converted to Java sql. Date
public class p10 {
    public static void main(String[] args){
        String date1="2020-09-08";

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date2=sdf.parse(date1);
            System.out.println(date2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
    "Fishing in three days and drying nets in two days"   1990-01-01  xxxx-xx-xx Fishing? Drying the net?
   public class p11 {
    public static void main(String[] args){     
        String date1="1990-01-02";//Start day
        String date2="19990-09-09";//same day

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");


        try {
            Date  date3=sdf.parse(date1);
            long time1= date3.getTime();
            long day1=time1/(1000*60*60*24)+1;

            Date  date4=sdf.parse(date2);
            long time2= date4.getTime();
            long day2=time2/(1000*60*60*24)+1;

            long day3=day2-day1;
            System.out.println(day3);

            int day4=(int)day3/5;

            if(day4<=3){
                System.out.println("I was fishing that day");
            }else
                System.out.println("I was drying my net that day");
            
        } catch (ParseException e) {
            e.printStackTrace();
        }
}

Calendar calendar class

  • Calendar is an abstract base class, which is mainly used to complete the mutual operation between date fields.
  • Method to get Calendar instance
    • Use calendar Getinstance() method
    • Call the constructor of its subclass GregorianCalendar.
  • An example of Calendar is the abstract representation of system time. The desired time information is obtained through the get(intfield) method. For example, YEAR, MONTH, DAY_OF_WEEK,HOUR_OF_DAY ,MINUTE,SECOND
    • public void set(intfield,intvalue)
    • public void add(intfield,intamount)
    • public final Date getTime()
    • public final void setTime(Date date)

LocalDate,LocalTime,LocalDateTime

  • Java 8 absorbs the essence of Joda-Time and creates a good API for Java with a new start. New Java Time contains all classes about local date, local time, local datetime, ZonedDateTime, and Duration.
  • LocalDate represents the date in IOS format (yyyy MM DD). It can store birthday, anniversary and other dates.
  • LocalTime represents a time, not a date.
  • LocalDateTime is used to represent date and time, which is one of the most commonly used classes.

common method

 @Test
    public void test1(){
        //now(): get the current date, time, date + time
        LocalDate LD=LocalDate.now();
        LocalTime LT=LocalTime.now();
        LocalDateTime LDT=LocalDateTime.now();

        System.out.println(LD);
        System.out.println(LT);
        System.out.println(LDT);

        //Set the specified month, day, hour, minute and second
        LocalDateTime localDateTime=LocalDateTime.of(2022,1,1,0,0,10,150);
        System.out.println(localDateTime);

        //Get time information
        System.out.println(localDateTime.getYear());

        //Set related properties
        LocalDateTime ldt=localDateTime.withHour(10);
        System.out.println(ldt.getHour());

        //Increase on the original basis
        LocalDateTime localDateTime2=localDateTime.plusMonths(2);
        System.out.println(localDateTime2);

        //Reduce on the original basis
        LocalDateTime localDateTime3=localDateTime.minusYears(2);
        System.out.println(localDateTime3);
    }

Instant class

  • Instant: an instantaneous point on the timeline. This may be used to record event timestamps in the application.
  • When dealing with time and date, we usually think of year, month, day, hour, minute and second. However, this is only a model of time, which is human oriented. The second general model is machine oriented, or continuous. In this model, a point in the timeline is represented as a large number, which is conducive to computer processing. In UNIX, this number has been in seconds since 1970; Similarly, in Java, it began in 1970, but in milliseconds.
  • java. The time package provides the machine view through the value type instant, and does not provide the time unit in the sense of processing human beings. Instant represents a point on the timeline without any contextual information, such as time zone. Conceptually, it simply represents the number of seconds since 0:0:0 (UTC) on January 1, 1970. Because Java Time package is based on Nanosecond calculation, so the accuracy of instant can reach nanosecond level.
  • common method

DateTimeFormatter class

  • java.time.format.DateTimeFormatter class: this class provides three formatting methods:
  • Predefined standard formats. E.g. ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
  • Localization related formats. For example: oflocalized datetime (formatstyle. Long)
  • Custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")

6. Java comparator

  • There are two ways to sort objects in Java:
    • Natural sorting: Java lang.Comparable
    • Custom sorting: Java util. Comparator

Comparable

  • For example, String and wrapper classes implement the Comparable interface, override the * * CompareTo (obj) * * method, and give a way to compare the sizes of two objects.
  • For example, String and wrapper classes are arranged from small to large after rewriting the compareTo() method
  • Rules for rewriting compareTo(obj):
    • If the current object this is greater than the formal parameter object obj, a positive integer is returned,
    • If the current object this is less than the formal parameter object obj, a negative integer is returned,
    • Returns zero if the current object this is equal to the parameter object obj.

User defined classes implement Comparable natural sorting

public class CompareTest {
    public static void main(String[] args){
        person p1=new  person("Tom",20,80);
        person p2=new  person("Jack",20,75);
        person p3=new  person("Smith",10,50);
        person p4=new  person("Ben",28,60);
        person p5=new  person("Curry",28,80);

        person[] arr=new person[]{p1,p2,p3,p4,p5};

        Arrays.sort(arr);

        for(person ppp:arr){
            System.out.println(ppp);
        }

    }
}


class person implements Comparable {
    String name;
    int age;
    int score;

    public person(String name,int age,int score){
        this.name=name;
        this.age=age;
        this.score=score;
    }

    @Override
    public String toString() {
        return "person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof person){
            person per=(person)o;

            //First, they are arranged from small to large according to their grades, and then from large to small according to their age
            int Score=Integer.compare(this.score,per.score);
            if(Score != 0){
                return Score;
            }else
                return -Integer.compare(this.age,per.age);

        }

        throw new RuntimeException("error in type");
    }
}

Comparator

  • When the element type does not implement Java Lang. comparable interface, and it is not convenient to modify the code, or it implements Java The collation of the lang. comparable interface is not suitable for the current operation, so you can consider using the Comparator object to sort
  • Rewrite the compare(Object o1,Object o2) method to compare the sizes 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.
 public void test4(){
        Goods[] arr = new Goods[6];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("huaweiMouse",224);
        arr[5] = new Goods("microsoftMouse",43);

        Arrays.sort(arr, new Comparator() {
            //Specify the way to compare the size of goods: sort according to the product name from low to high, and then sort according to the price from high to low
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Goods && o2 instanceof Goods){
                    Goods g1 = (Goods)o1;
                    Goods g2 = (Goods)o2;
                    if(g1.getName().equals(g2.getName())){
                        return -Double.compare(g1.getPrice(),g2.getPrice());
                    }else{
                        return g1.getName().compareTo(g2.getName());
                    }
                }
                throw new RuntimeException("The data type entered is inconsistent");
            }
        });

        System.out.println(Arrays.toString(arr));
    }

Comparison between Comparable interface and Comparator:

  • Once the method of the Comparable interface is fixed, it can ensure that the objects of the implementation class of the Comparable interface can be compared in size at any position.
  • The Comparator interface is a temporary comparison.

7. System class

  • The System class represents the System. Many System level properties and control methods are placed inside this class. This class is located in 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 they can also be called conveniently.
  • Member variable
    • The System class contains three member variables: in, out and err, which represent standard input stream (keyboard input), standard output stream (display) and standard error output stream (display) respectively.
  • Member method
    • native long currentTimeMillis():
      The function of this method is to return the current computer time. The expression format of time is the millisecond difference between the current computer time and GMT (Greenwich mean time) on January 1, 1970.
    • void exit(int status):
      The function of this method is to exit the program. The value of status is 0, which represents normal exit, and non-zero represents abnormal exit. Using this method, the exit function of the program can be realized in the graphical interface programming.
    • void gc():
      The function of this method is to request the system for garbage collection. Whether the system recycles immediately depends on the implementation of the garbage collection algorithm in the system and the execution of the system.
    • getProperty(String key):
      This method is used to obtain the value corresponding to the attribute named key in the system. The common attribute names and functions in the system are shown in the following table:

8. Math class

nameuse
double Random()Randomly generate a decimal between [0, 1]
double sqrt(double num)Returns the root number of num
double cbrt(double num)Returns the cube root value of num
double pow( double a , double b)Returns the power b of a
double max(double a, double b)Returns the larger one between a and b
double min (double a , double b)Returns the smaller one between a and b
double abs(double a)Returns the absolute value of a

Randomly generate an integer between [M, n]

int num= (int)(Math.Random()*(n-m+1)+m);

Keywords: Java Back-end

Added by felixtgomezjr on Thu, 13 Jan 2022 18:18:27 +0200