Shang Xue School Video Notes IV: Common Classes

Common Classes

1. Packaging Classes

1.1 Basic knowledge of packaging

java is an object-oriented language, but it is not "object-only" because the basic data types we often use are not objects.But in practice, we often need to convert basic data types into objects for easy operation.For example, operations that store basic data types in Object [] data or collections, and so on.

To address this shortage, Java designs classes that are represented by a corresponding class for each basic data type, so that the eight corresponding classes for the basic type are collectively referred to as Wrapper Classes.

Packaging classes for basic data types

Basic data types Packaging Class
byte Byte
boolean Boolean
short Short
char Character
int Integer
long Long
float Float
double Double

Of the eight class names, except for the Integer and Character classes, the class names of the other six classes are identical to the basic data type, except that the first letter of the class name is capitalized.

Of the eight classes, all except the Character and Boolean classes are numeric, and the numeric is a subclass of java.lang.Number.Number class is an abstract class, so its abstract method, all subclasses need to provide implementation, Number class provides Abstract methods: intValue(), longValue(), floatValue(), doubleValue(), which means that all "digital" wrapper classes can be transformed from one another.

The following is an example of a packaging class:

package com.helloworld;

public class TestWrapperClass {

    public static void main(String[] args) {
        // Basic data type to wrapper class object
        Integer a = new Integer(3);
        Integer b = Integer.valueOf(30);// This is generally recommended

        // Convert Packaging Class to Basic Data Type
        int c = b.intValue();
        double d = b.doubleValue();

        // Converts a string to a wrapper class object
        Integer e = new Integer("9999");
        Integer f = Integer.parseInt("10101001", 2);
        System.out.println(f + " ");

        // Convert wrapper class to string
        String str = f.toString();

        // Common constants
        System.out.println("int Integer of the largest type: " + Integer.MAX_VALUE);



1.2 Automatic packing and unloading

Automatic unboxing and unboxing is the automatic conversion between basic data types and packaging classes.After JDK1.5, Java introduced autoboxing and unboxing

Automatic packing:

Basic data types are automatically converted to "objects" when they are in an environment where objects are needed.

Automatic unboxing:

When a value is required, the object is automatically converted to a basic data type, so it is not necessary to call transformation methods such as intValue(), doubleValue() on the display.

The auto-loading process is achieved by calling the valueOf() method of the wrapper class, while the auto-unboxing process is achieved by calling the xxxValueOf() method of the wrapper class (xxx represents the corresponding basic data types, such as intValue(), doubleValue(), and so on).

1.3 String Class

String objects represent Unicode character sequences of immutable classes, so String objects become immutable.

In the String class:

public final class String
	implements, Comparable<String>, CharSequence {
		private final char value[];

The core is private final char value[].Because of the final modification, String objects can only be assigned once at initialization, which is why String objects are immutable.

When stitching between string constants is encountered, the compiler optimizes that string stitching is done during compilation.Therefore, when comparing String objects using ==we need to pay special attention to:

package CommonClass;

public class StringTest {

    public static void main(String[] args) {

        // The compiler is optimized to splice strings directly at compile time
        String str1 = "hello" + "java";//Equivalent to hellojava
        String str2 = "hellojava";
        System.out.println(str1 == str2);

        String str3 = "hello";
        String str4 = "java";
        String str5 = str3 + str4;
        // There is no way to optimize at compile time because you do not know what is stored in the variable at compile time.
        System.out.println(str2 == str5);


StringBuiler class

In StringBuilder source code:

abstract class AbstractStringBuilder implements Appendable, CharSequence {
    char[] value;
    int count;

char[] value is not decorated with final, which means that objects created by the StringBuilder class can be modified

package CommonClass;

public class StringBuilderClass {

    public static void main(String[] args) {
        String str;

        //StringBuilder threads are insecure and efficient; StringBuffer threads are safe but inefficient, and StringBuilder classes are generally used
        StringBuilder sb = new StringBuilder("absgcesf");


        sb.setCharAt(2, 'M');
        sb.setCharAt(5, 'C');


Common methods:

StringBuilder.reverse();// Reverse order
StringBuilder.setCharAt(int index, char str);// Modify character at specified position
StringBuilder.insert(int offset, char c);// Insert at the specified location, and since it returns itself, it can be called chained
StringBuilder.delete(int start, int end);// Deletes the specified interval.Also return to itself for chain call

Traps for immutable and variable strings:

StringBuilder is used to stitch strings. If you stitch strings using a for loop, a large amount of memory and time will be wasted.

So using the SringBuilder.append() method to loop through the accumulated strings saves space and time.

1.4 Time processing related classes:

In the world of computers, we locate the base time at 00:00:00 on January 1, 1970, in milliseconds per unit of measure

We use long variables to represent time, hundreds of millions of years from the base time to hundreds of millions of years from now.If you want to get the "moment value" of the present moment, you can use:

long now = System.currentTimeMillis();

This "time array" is the core value of all time classes, and the year, month and day are calculated from this "value".The time-related categories involved in our work and study are as follows:

[External chain picture transfer failed (img-2EshJUqi-156541431) (E:DocumentjavaJAVE EESchool NotesDepth Screenshot_Selection Area_2017071931.png)]

Common methods:

Core-Date.getTime() gets milliseconds

Since many of the methods in Date have been obsolete (replaced by Calendar), you can just master the core.Many of these string-related methods have also been replaced by DateFormat.

1.5 DateFormat and SimpleDateFormat

Among them, SimpleDateFormat is the implementation class of DateFormat, and we generally use SimpleDateFormat in practice.

  • Role of the DateFormat class

    Converts a time object to a string in a specified format.Conversely, convert the specified format string to an event object.

    DateFormat is an abstract class that is generally implemented using its subclass SimpleDateFormat.

    Specific meaning of format conversion characters in code:

    Letter Date or time elements Express Example
    G Era Marker Text AD
    y year Year 1996; 96
    M Month of year Month July; jul; 07
    w Weeks in the year Number 27
    W Weeks in Month Number 2
    D Days in year Number 189
    d Number of days in month Number 10
    F Weeks in Month Number 2
    E Days of the week Text Tuesday; Tue
    a Am/pm tag lizi Text Pm
    H Hours in a day (0-23) Number 0
    k Hours in a day (1-24) Number 24
    K Hours in am/pm (0-11) Number 0
    h Hours in am/pm (1-12) Number 12
    m Minutes in an hour Number 30
    s Seconds in minutes Number 55
    S Msec Number 978
    z time zone General time zone Pacific Standard Time; PST; GMT-08:00
    Z time zone RFC 822 time zone 0800
  • Some examples

package CommonClass;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

 * Testing the conversion between time objects and strings
public class TestDateFormat {

    public static void main(String[] args) throws ParseException {
        // Converts the time to a string in the specified format
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String str = df.format(new Date());

        // Converts a string into a time object in response format
        DateFormat df2 = new SimpleDateFormat("yyyy year MM month dd day hh:mm:ss");
        Date date = df2.parse("1983 12 May 10, 2001:55:30");
        //Test other formatting characters.For example, with D, get is now the day of the current year.
        DateFormat df3 = new SimpleDateFormat("D");
        String str3 = df3.format(new Date());

* 2019-07-07 08:46:12
* Tue May 10 00:55:30 CST 1983
* 188

* If java.text.ParseException is thrown: Unparseable date: "****"
* Indicates that the date you entered is in the wrong format

1.6 Calendar Date Class

The Calendar class is an abstract class that provides us with functions related to date calculations.For example, year, month, day, hour, minute, second display and calculation.

Gregorian Calendar is a specific subclass of Calendar that provides the standard calendar system used in most countries in the world.

  • Newbie minefield

Notice the month, January is 0, February is 1, and so on, December is 11.Since most people are used to using words instead of numbers to represent months, programs may be easier to read, and parent Calendar s use constants to represent months: JANUARY, FEBRUARY, and so on.

  • Some examples

package CommonClass;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

 * Use of test date class

public class TestCalendar {

    public static void main(String[] args) {

        Calendar calendar = new GregorianCalendar(2999,10,9,22,10,50);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int whichDay = calendar.get(Calendar.DAY_OF_WEEK);
        int day = calendar.get(Calendar.DATE); // DATE_OF_MONTH can also be used
        System.out.println(whichDay);// Monday 1-7 1-Sunday 2-Monday 7-Sunday
        System.out.println(month);//0-11 means the corresponding month 0-January 11-December

        //Set date related elements
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, 9102);


        //Date calculation
        Calendar c1 = new GregorianCalendar();
        c1.add(Calendar.DATE, 100);

        //Conversion of date and time objects
        Date d4 = c1.getTime();
        Calendar c2 = new GregorianCalendar();

// Result
Tue Oct 15 21:27:23 CST 2019
  • Simple Visual Calendar

package CommonClass;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.concurrent.CancellationException;

 * Visualize Calendar Procedures
public class TestCalendarHomeWork {

    public static void main(String[] args) throws ParseException {
        System.out.println("Please enter the date: 2020-9-10");
        Scanner sc = new Scanner(;
        String str = sc.nextLine();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date =  df.parse(str);
        Calendar c = new GregorianCalendar();

        System.out.println("day\t one\t two\t three\t four\t five\t six");

        int today = c.get(Calendar.DAY_OF_MONTH);

        c.set(Calendar.DAY_OF_MONTH, 1);

        for (int i = 0; i < c.get(Calendar.DAY_OF_WEEK) -1; i++) {

        int maxDay = c.getActualMaximum(Calendar.DATE);

        for (int i = 0; i < maxDay; i++) {

            if(today == c.get(Calendar.DAY_OF_MONTH)){
                System.out.print(c.get(Calendar.DAY_OF_MONTH) + "*\t");
            else {
                System.out.print(c.get(Calendar.DAY_OF_MONTH) + "\t");
            if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
                System.out.println("\t"); //Line Break Operation

            c.add(Calendar.DAY_OF_MONTH, 1);


Please enter a date: 2020-9-10
 Day 1 2 3 4 5 6
		1	2	3	4	5		
6	7	8	9	10*	11	12		
13	14	15	16	17	18	19		
20	21	22	23	24	25	26		
27	28	29	30	

1.7 Basic usage of File class

The class: represents files and directories.This class is often used in development when reading files, generating files, deleting files, and modifying the properties of files.

Common construction methods for File classes: public File(String pathname)

Create a File object with pathname as the path, and if pathname is a relative path, the default current path is stored in the system property user.dir.

package CommonClass;

import java.util.Date;

 * Testing the basic usage of File classes
public class TestFile {

    public static void main(String[] args) throws IOException {

        File f = new File("/home/qianqian/txt.txt");
        f.renameTo(new File("/home/qianqian/aa.txt"));


        File f2 = new File("gg.txt");

        System.out.println("File Is there: " + f2.exists());
        System.out.println("File Is it a directory:" + f2.isDirectory());
        System.out.println("File Is it a file:" + f2.isFile());
        System.out.println("File Size:" + f2.length());
        System.out.println("File Last Modification Time:" + new Date(f2.lastModified()));
        System.out.println("File Filename:" + f2.getName());
        System.out.println("File Directory Root Path:" + f2.getAbsolutePath());

//        f2.delete();

        File f3 = new File("01/02/03");

        if(f3.exists()) {


        File f4 = new File("01/02");

        File f5 = new File("01");


File Class - Recursive Print Directory Tree Structure

package CommonClass;


 * Printing a directory tree using a recursive algorithm
public class TestPrintFileTrees {

    public static void main(String[] args) {
        File f = new File("/media/qianqian/New Volume/Document/self-learning");

    static void printFile(File file, int level) {

        for (int i = 0; i < level; i++) {
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for(File temp : files) {
                printFile(temp, level + 1);


1.8 Enumerations

JDK1.5 introduces enumeration types.The definition of an enumeration type includes an enumeration declaration and an enumeration body.The format is as follows

enum enumeration name {
    Enumerator (Constant List)

An enumeration is the placement of constants.We can write out our first enumeration type.

enum Season {

All enumeration types implicitly inherit from java.lang.Enum.Enumerations are essentially classes!Each enumerated member is essentially an instance of an enumerated type, which is decorated with public static final by default.They can be used directly by enumerating type names.


  1. Enumeration types can be used when you need to define a set of constants.
  2. Try not to use advanced features of enumeration types. In fact, advanced features can be implemented using ordinary classes. There is no need to introduce enumerations to increase program complexity.
package CommonClass;

 * Test Enumeration
public class TestEnum {

    public static void main(String[] args) {

        Season a = Season.AUTUMN;

        switch (a) {
            case SPRING:
                System.out.println("Now, it's Spring.");
            case SUMMER:
                System.out.println("Now, it's Summer");
            case AUTUMN:
                System.out.println("Now, it's Autumn");
            case WINTER:
                System.out.println("Now, it's Winter");


enum Season {

enum Week {

Tags: Java Spring

Posted on Fri, 09 Aug 2019 22:23:27 -0700 by mallen