Java common classes (entry level)

Posted by doofystyle on Sun, 09 Jan 2022 08:06:29 +0100

1. String class:

1) String/StringBuffer/StringBuilder are three classes that represent strings.
2) String: immutable String. The bottom layer is implemented with char [] decorated with final, and the length cannot be changed.
3) all methods of StringBuffer are decorated with synchronized, so it is thread safe, and StringBuffer is non thread safe.
4) in terms of speed, StringBuilder > StringBuffer > string. Therefore, StringBuffer/StringBuilder should be used when processing strings with large amount of data. At the same time, if it is multithreaded, thread safety should be considered.

About immutable string: the following figure is collected on the official website of power node, which can be understood by beginners:

Common operation: these methods are commonly used but not easy to remember. (in fact, most methods in Java can judge their functions according to the method name). Only a few methods are listed here. If you want to know more, you can also refer to the following documents:

jdk Chinese help document

Method typeMethod nameDescription
static Stringformat("%04d-%02d-%02d", year,month, day)Returns a format controlled string.
String      replace(char old, char new)

Returns a new string by replacing it with new

From all old that appear in.

String []     split(String regex, int limit) : Splits the string based on matching the given regular expression.
bolean       startsWith(String prefix): Tests whether this string starts with the specified prefix.
CharSequence subSequence(int beginIndex, int endIndex) : Returns a new character sequence, which is a subsequence of this sequence.
String      substring(int beginIndex)Returns a new string, which is a substring of this string.
boolean    contains(CharSequence s)

Returns true if and only if this string contains the specified sequence of char values

Sometimes we can use it to simply judge whether a sequence is a substring of another string.

A CharSequence is mentioned in the above method
public interface CharSequence: a readable sequence of char values. This interface provides unified read-only access to many different kinds of char sequences. If you want to have an in-depth understanding, you can also view the documents, which is not necessary for beginners.
  

2. Wrapper class: Java provides a corresponding wrapper class for each basic data type

Basic typePackaging
     byte        Byte
short        Short
int            Integer
long        Long
float        Float
double        Double
char        Character
boolean        Boolean
/*
 static int bitCount(int i)
          Returns the number of 1 bits of the binary complement representation of the specified int value.
 byte byteValue()
          Returns the value of the Integer as byte.
 int compareTo(Integer anotherInteger)
          Compares two Integer objects numerically.
 static Integer decode(String nm)
          Decode String to Integer.
 double doubleValue()
          Returns the value of the Integer as double.
 boolean equals(Object obj)
          Compares this object with the specified object.
 float floatValue()
          Returns the value of the Integer as float.
 `````

 */
public class IntegerTest {
    public static void main(String[] args) {
        //The following fields are static constants.
        System.out.println(Integer.MAX_VALUE);//2147483647, that is, the signed maximum value represented by an integer
        System.out.println(Integer.MIN_VALUE);//-2147483648, that is, the integer represents the minimum value

        //Create an Integer object.
        Integer integer = 100;//Of course, you can also construct an Integer object like this: Integer = new Integer (100);
        System.out.println(integer.intValue());//100
    }
}

  

Why provide packaging class:

As we all know, Java is an object-oriented high-level programming language. Object-oriented has many characteristics and attributes, but it is not 100% object-oriented, such as these eight basic data types. Therefore, Java provides their own wrapper classes for these basic data types. In this way, these basic data types also have some object-oriented characteristics and commonalities.

For example, the wrapper type Integer class of int inherits Number and, of course, Object class. The Comparable interface is implemented, and the fields are:

                MAX_VALUE: represents the maximum value that the int type can represent.
                 MIN_VALUE: represents the minimum value that the int type can represent.
SIZE: used to represent the bit number of int value in the form of binary complement.
TYPE: represents the Class instance of the basic TYPE int.
There are many other ways. Not one by one here. Other basic types can be understood by comparison.

We convert a basic type to a packing type, which is called packing, and the reverse is called unpacking. In Java, boxing and unpacking can be done automatically, so in most cases, we don't need to create objects of packing classes manually.

3. Java date and time type: in terms of time, no matter from which discipline, it will be very difficult to study deeply and pursue considerable accuracy. As big as celestial universe, as small as minutes and seconds. There are several classes about time in Java. There are many descriptions and explanations of these classes and interfaces about time in the official jdk documents, and we don't need to go deep into them.

     1)java.util.Date class: the date class represents the specified number of milliseconds since the standard base time (called epoch), that is, 00:00:00 GMT, January 1, 1970).


     2)java.text.SimpleDateFormat class: a concrete class that formats and parses dates in a locale dependent manner. It allows formatting (date - > text), parsing (text - > date), and normalization. SimpleDateFormat allows you to select any user-defined date time format pattern. However, it is still recommended to create a date time formatter through getTimeInstance, getDateInstance, or getDateTimeInstance in DateFormat.

public class Test01 {

    public static void main(String[] args) throws ParseException {
        //Create a Date object that represents the current time. Output format: Fri Dec 10 15:20:46 CST 2021
        Date date = new Date();
        System.out.println(date);//Sun Jan 09 13:57:24 CST 2022

        // Convert the date object date to a string in the given format: "yyyy MM dd HH:mm:ss SSS".
        // The yyyy, MM, dd and other symbols here are set in the SimpleDateFormat class, and only such symbols can be recognized. There are other symbols to view
        // api documentation for the SimpleDateFormat class.
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss SSS");
        System.out.println(sdf.format(date));  // January 9, 2022 13:57:24 053

        //Converts the given string to a Date object.
        String text = "2035-10-10 00:15:12";
        //Note: the format string must exactly match the date string
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date = sdf.parse(text);
        System.out.println( date );//  Wed Oct 10 00:15:12 CST 2035

        //Gets the current calendar. This object is a calendar set at the current time
        Calendar calendar1 = Calendar.getInstance();
        //  Use set() to set a calendar.
        calendar1.set(2200,6,6);
        int year = calendar1.get(Calendar.YEAR);
        int month = calendar1.get(Calendar.MONTH);
        int day = calendar1.get(Calendar.DAY_OF_MONTH);
        
        System.out.println( year+"-"+month+"-"+day);   //  2200-6-6
    }
}


     3)java.util.Calendar Class: class is an abstract class, which is associated with a group such as YEAR, MONTH and day for a specific moment_ OF_ The conversion between calendar fields such as MONTH and HOUR provides some methods, and provides some methods for operating calendar fields (such as obtaining the date of the next week). The moment can be expressed in milliseconds, which is the offset from the epoch (i.e. 00:00:00.000 Greenwich mean time on January 1, 1970, Gregorian calendar). This class also provides other fields and methods for implementing specific calendar systems outside the scope of the package. These fields and methods are defined as protected. Like other locale sensitive classes, calendar provides a class method getInstance to obtain a common object of this type. The getInstance method of calendar returns a calendar object whose calendar field has been initialized by the current date and time:
                           Calendar rightNow = Calendar.getInstance();
The Calendar object can generate all Calendar field values required for date time formatting in a specific language and Calendar style, such as Japanese Gregorian Calendar and Japanese traditional Calendar.
Calendar defines the range of return values of some calendar fields and the meaning of these values. For example, for all calendars, the value of the first month of the calendar system is MONTH == JANUARY.
For beginners like me, it's enough to use the Calendar class to create a Calendar, and then operate on the information of year, month, day and week.

/*
    There are the following properties in Calendar:
    YEAR Indicates the year. MONTH indicates the MONTH.
    DAY_OF_MONTH Indicates a day of the month.
    DAY_OF_WEEK Indicates a day of the week.
    DAY_OF_YEAR Indicates the number of days in the current year.
    DAY_OF_WEEK_IN_MONTH Indicates the week ordinal of the current month.
    HOUR Indicates an hour of the day. MINUTE indicates a MINUTE of the current hour
    SECOND Indicates a second in the current minute
    be careful:
        The month is 0 ~ 11; In the west, people think Sunday is the beginning of a week, so 1 ~ 7 respectively mean Sunday to Saturday.
    Common methods include get(),set(); We can understand it with the help of a topic of the Blue Bridge Cup in previous years:
        The question of the end of the world: some cults once said that December 31, 1999 was the end of the world. Of course, the rumor has been broken. Others say
    December 31, the end of a century in the future, if it is Monday, it will... Interestingly, December 31 of any year at the end of a century will be
    It can't be Monday!! Therefore, the "rumor manufacturer" is revised to Sunday... December 31, 1999 is Friday. May I ask: the future
    Which is the last year of the century (i.e. xx99) from us? December 31 happens to be Sunday (i.e. Sunday)?
 */
public class Test02 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        for (int year = 1999; year < 10000; year+=100) {
            calendar.set(year,11,31);//As mentioned earlier, the month starts from 0, so set month to 11
            if (calendar.get(Calendar.DAY_OF_WEEK)==1){
                System.out.println(year);         //year = 2299
                break;
            }
        }
    }
}

    4,java.lang.Math class: defines some methods related to mathematical functions.

      1)java.text.DecimalFormat class:

2)BigInteger/BigDecimal class: these two classes are used when scientific calculation / financial calculation requires high precision;

      3)java.util.Random class: used to generate random numbers

public class Test03 {
    public static void main(String[] args) {
        //1) Math.random() generates random decimals between [0,1]
        for(int i = 0 ;  i<10 ; i++){
            System.out.println( Math.random() );
        }

        //2)
        System.out.println( Math.sqrt(100)); 	//square root
        System.out.println( Math.cbrt(100));	//Cube root
        System.out.println( Math.pow(3, 4));	//The fourth power of 3

        //3)
        System.out.println( Math.ceil( 5.6 ));  		//Returns the minimum integer 6.0 greater than or equal to the specified number
        System.out.println( Math.floor( 5.6 ));			//Returns the maximum integer 5.0 less than or equal to the specified number

        //4) Two constants
        System.out.println( Math.PI);
        System.out.println( Math.E);
    }
}


    
 

Topics: Java Back-end