java learning notes fourth week

catalogue

1, Common class

1. Packaging

1.1 initial knowledge of packaging

1.2 purpose of packaging

1.3 use of packaging

1.4 automatic packing and unpacking

1.5 caching of packaging

2. String related classes

2.1 source code analysis of string class

2.2 StringBuffer and StringBuilder

2.3 common methods of StringBuilder (key points)

3. Time processing related classes

3.1 Date class

3.2 use of dateformat class and SimpleDateFormat class

3.3 use of calendar

4. Math class

5. Random class

6. File class

6.1 creating files using the File class

6.2 use File class to access File or directory attributes

6.3 create an empty File or directory through the File object

7. Enumeration

7.1 creating enumeration types

7.2 use of enumeration

8. Recursive printing directory tree structure

1, Common class

1. Packaging

Java is an Object-oriented language, but it is not "pure Object-oriented", because the basic data type we often use is not an Object. However, in practical applications, we often need to convert basic data into objects for easy operation. For example, the operation of storing basic data types into Object [] arrays or collections. In order to solve this problem, Java designs a corresponding class for each basic data type to represent when designing the class. In this way, the eight classes corresponding to the basic data type are collectively referred to as wrapperclass.

 

 

1.1 initial knowledge of packaging

package studyweek4;
//Packaging
public class study1 {
    public static void main(String[] args) {
        Integer i=new Integer(100);//java9 was abandoned later
    }
}

1.2 purpose of packaging

For the packaging category, there are two main uses of these categories:

1. It exists as a type corresponding to the basic data type, which is convenient for operations involving objects, such as Object [], set, etc.

2. Include the relevant attributes of each basic data type, such as maximum value, minimum value, etc., and relevant operation methods (these operation methods are used to provide mutual conversion between basic data types, wrapper objects and strings!).

1.3 use of packaging

package studyweek4;
//Packaging
public class study1 {
    public static void main(String[] args) {
        //Convert basic data type to wrapper class object
        Integer int1 = new Integer(100);//java9 was abandoned later
        Integer int2 = Integer.valueOf(20);//This method is officially recommended

        //Convert wrapper class object to basic data type
        int a = int1.intValue();
        double d = int2.doubleValue();

        //Convert string type to wrapper object (both methods can)
        Integer int3=Integer.valueOf("234");//Overload of valueof
        Integer int4=Integer.parseInt("999");

        //Convert wrapper class object to string
        String str=int3.toString();//ToString method of wrapper class string STR = integer toString(10);

        //Some common constants
        System.out.println(Integer.MAX_VALUE);//Returns the maximum integer that the int type can represent
        System.out.println(Integer.MIN_VALUE);//Returns the smallest integer that type int can represent

    }
}

1.4 automatic packing and unpacking

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

Automatic packing:

When the basic type of data is in the environment where an object is needed, it is automatically converted to "object". Let's take Integer as an example: in jdk1 Before 5, such code Integeri=5 was wrong. The process of converting basic data types into wrapper classes must be realized through statements such as Integeri=newInteger(5); And in jdk1 After 5, Java provides the function of automatic boxing, so only statements such as Integeri=5 can convert basic data types into wrapper classes, because the JVM executes integeri = Integer for us The operation of valueof (5) is the automatic boxing of Java.

Automatic unpacking:

Whenever a value is needed, the object will be automatically converted to the basic data type. There is no need to explicitly call transformation methods such as intValue(), doubleValue(). For example, Integeri=5;intj=i; This process is automatic unpacking.

We can summarize the automatic packing / unpacking in one sentence: the automatic packing process is realized by calling the valueOf() method of the packing class, while the automatic unpacking process is realized by calling the xxxValue() method of the packing class (xxx represents the corresponding basic data type, such as intValue(), doubleValue(), etc.).

//Automatic packing and unpacking
public class study1{
    public static void main(String[] args) {
        //Automatic packing
        Integer a=200;//The compiler changed it to integer a = integer valueOf(200);

        //Automatic unpacking
        int b=a;//Compiler changed to a.intValue();

        //Error code
        Integer c=null;//Empty objects cannot call methods!!
        int c2=c;//The compiler is changed to c.intvalue()// "Java.lang.nullpointerexception: the object is null. We called its property or method

    }
}

1.5 caching of packaging

The packing class corresponding to integer type and char type will be cached for values between - 128 ~ 127 during automatic packing in order to improve efficiency.

The principle of cache processing is: if the data is in the range of - 128 ~ 127, an object has been created for each value in the range when the class is loaded, and the 256 objects are stored in an array called cache. Whenever the automatic packing process occurs (or when valueOf() is called manually), it will first judge whether the data is in this interval. If it is, it will directly obtain the reference of the corresponding packaging class object in the array. If it is not in this interval, it will call the construction method of packaging class through new to create the object.

    //Cache problem of packaging
        Integer d1=4000;
        Integer d2=4000;
        Integer d3=123;//When the data is between - 128 and 127, the compiler will take the object from the array, so it returns an element in the cache array
        Integer d4=123;//It is also taken from the cache array and is consistent with the previously taken object.

        System.out.println(d1==d2);//false
        System.out.println(d3==d4);//true
        System.out.println(d1.equals(d2));//true;

2. String related classes

String class, StringBuilder class and StringBuffer class are three string related classes. String class is an object representing immutable character sequences, while StringBuilder class and StringBuffer class represent variable character sequences. The detailed usage of these three classes is often used in written examination, interview and actual development. We must master them.

2.1 source code analysis of string class

String class objects represent immutable Unicode character sequences, so we can call string objects "immutable objects". What is "immutable object"? It means that the value of the member variable inside the object can no longer be changed. We open the source code of the string class,

We found that all the string contents are stored in the value [] array, and the variable value is of type final, that is, a constant (that is, it can only be assigned once). This is the typical definition of "immutable object".

We found that some methods of learning String earlier, such as substring() is a String interception operation, but the essence is to read the content of the original String and generate a new String.  

Supplement: optimization of string constant splicing

The common methods of String class are (as mentioned earlier, it will not be repeated here):

 the following methods of String class can create and return a new String object: concat(), replace(), substring(), toLowerCase(), toUpperCase(), trim().

 provide relevant methods of search function: endsWith(), startsWith(), indexOf(), lastIndexOf().

 methods to provide comparison functions: equals(), equalsIgnoreCase(), compareTo().

 other methods: charAt(), length().

2.2 StringBuffer and StringBuilder

StringBuffer is very similar to StringBuilder. Both represent variable character sequences. These two classes are as like as two peas of abstract class AbstractStringBuilder.

Obviously, the interior is also a character array, but this character array is not decorated with final and can be modified at any time. Therefore, StringBuilder and StringBuffer call them "variable character sequences". What's the difference between the two?

StringBufferJDK1. The class provided by version 0 is thread safe and does thread synchronization check, which is inefficient.

StringBuilderJDK1. The class provided in version 5 is thread unsafe and does not do thread synchronization check, so it is more efficient. It is recommended to use this type of.

2.3 common methods of StringBuilder (key points)

At present, we mainly learn the append method well!

package studyweek4;

public class study2 {
    public static void main(String[] args) {
        String s1=new String("abcdef");
        String s2=s1.substring(2,4);
        System.out.println(Integer.toHexString(s1.hashCode()));

        String str="aabb";//Immutable character sequence
        //StringBuilder sb=null;// Immutable character sequence
        //StringBuffer sb2=null;// Immutable character sequence

        //Common methods of StringBuilder and StringBuffer
        //append;
        StringBuilder sb=new StringBuilder("ji");
        sb.append(123);
        sb.append(456);
        System.out.println(sb);//ji123456
        sb.append("aa").append("bb").append("cc");//Because every one After append, sb is returned, so it becomes sb again at the end of each time append
        System.out.println(sb);//ji123456aabbcc

        //The following methods also apply to StringBuilder
        //Insert insert
        StringBuffer sb2=new StringBuffer("java");
        sb2.insert(0,"love").insert(0,"I");
        System.out.println(sb2);

        //Delete delete substring
        sb2.delete(0,2);
        System.out.println(sb2);

        //deleteCharAt(x) deletes a character
        sb2.deleteCharAt(0).deleteCharAt(0);
        System.out.println(sb2.charAt(0));//Get a character

        //String reverse order
        System.out.println(sb2.reverse());

    }
}

Note: if String splicing is required, try to use StringBuilder instead of String. As can be seen from the following code, StringBuilder occupies significantly less memory and time.

package studyweek4;

public class study3 {
    public static void main(String[] args) {
        /**Use String to splice strings*/
        String str="";
        //StringBuilder splicing is essentially used, but each loop generates a StringBuilder object
        long num1=Runtime.getRuntime().freeMemory();//Get the remaining memory space of the system
        long time1=System.currentTimeMillis();//Get the current time of the system
        for(int i=0;i<5000;i++){
            str=str+i;
        }
        long num2=Runtime.getRuntime().freeMemory();
        long time2=System.currentTimeMillis();
        System.out.println("String Occupied memory"+(num2-num1));
        System.out.println("String Occupation time"+(time2-time1));
        /**String splicing using StringBuilder*/

        StringBuilder sb1=new StringBuilder();
        long num3=Runtime.getRuntime().freeMemory();//Get the remaining memory space of the system
        long time3=System.currentTimeMillis();
        for (int i=0;i<5000;i++){
            sb1.append(i);
        }
        long num4=Runtime.getRuntime().freeMemory();
        long time4=System.currentTimeMillis();
        System.out.println("StringBuilder Occupied memory"+(num4-num3));
        System.out.println("StringBuilder Occupation time"+(time4-time3));

    }
}

3. Time processing related classes

3.1 Date class

      //Are calculated in milliseconds
        long a=Long.MAX_VALUE/(1000L*365*3600*24);
        System.out.println(a);//About 290 million years later
        long now=System.currentTimeMillis();//Represents the number of milliseconds at the current time
        System.out.println(now);

        Date d1=new Date();  //There is no transmission parameter, which represents the current moment
        System.out.println(d1);
        System.out.println(d1.getTime());

        Date d2=new Date(1000L*3600*24*365*250); //250 years after 1970
        System.out.println(d2);

3.2 use of dateformat class and SimpleDateFormat class

 //DateFormat and SimpleDateFormat

        //Format object
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//The format can also add yyyy year, etc
        //Converts a string to a Date object
        Date d11= df.parse("2022-2-4 15:00:20");
        System.out.println(d11.getTime());

        //Converts a Date object to a string
        Date d22=new Date(1000L*3600*23);
        String str11=df.format(d22);
        System.out.println(str11);

        DateFormat df2=new SimpleDateFormat("The first of this year w week");
        System.out.println(df2.format(d11));

Possible formatting characters in Code:

3.3 use of calendar

    //Calendar calculation date
package studyweek4;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;//Import of Date class
import java.util.GregorianCalendar;

public class study3 {
    public static void main(String[] args) throws ParseException {//Handling exceptions will be learned later
        GregorianCalendar calendar=new GregorianCalendar(2022,1,5,0,5);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH);
        int day=calendar.get(Calendar.DAY_OF_MONTH);
        int day2=calendar.get(Calendar.DATE);
        int date=calendar.get(Calendar.DAY_OF_WEEK);//Day of week

        System.out.println(year);
        System.out.println(month);
        System.out.println(day);
        System.out.println(day2);
        System.out.println(date);

        //Set date
        GregorianCalendar calendar2=new GregorianCalendar();
        calendar2.set(Calendar.YEAR,1999);
        calendar2.set(Calendar.MONTH,Calendar.SATURDAY);//Number of months: 0-11;
        calendar2.set(Calendar.DATE,3);
        calendar2.set(Calendar.HOUR_OF_DAY,10);
        calendar2.set(Calendar.MINUTE,20);
        calendar2.set(Calendar.SECOND,23);
        printCalendar(calendar2);

        GregorianCalendar calendar3=new GregorianCalendar(1999,10,9,22,10,50);
        calendar3.add(Calendar.MONTH,-7);
        calendar3.add(Calendar.DATE,7);
        printCalendar(calendar3);

        Date d=calendar3.getTime();
        GregorianCalendar calendar4=new GregorianCalendar();
        calendar4.setTime(new Date());
    }

        static void  printCalendar(Calendar calendar){
            int year=calendar.get(Calendar.YEAR);
            int month=calendar.get(Calendar.MONTH)+1;
            int day=calendar.get(Calendar.DAY_OF_MONTH);
            int date=calendar.get(Calendar.DAY_OF_WEEK)-1;//What day is today?
            String week=""+((date==0)?"day":date);
            int hour=calendar.get(Calendar.HOUR);
            int minute=calendar.get(Calendar.MINUTE);
            int second=calendar.get(Calendar.SECOND);
            System.out.printf("%d year%d month%d day,week%s  %d:%d:%d\n",year,month,day,week,hour,minute,second);
        }

    }

4. Math class

5. Random class

6. File class

The File class is used to represent files

Basic usage of File class:

java.io.File class: represents files and directories. In development, this class is often used when reading files, generating files, deleting files, and modifying file attributes.

6.1 creating files using the File class

package studyweek4;
//File class use

import java.io.File;
import java.io.IOException;

public class FIle class {
    public static void main(String[] args) throws IOException {
        File f1=new File("D:/java.txt");//create a file
        File f2=new File("D:\\java.txt");//When creating a file, the backslash is an escape character, so it takes two characters

        f1.createNewFile();

        System.out.println(System.getProperty("user.dir"));//Get project path
        File f3=new File(System.getProperty("user.dir"));//f3 stands for this project
        
    }
}

6.2 use File class to access File or directory attributes

public class FIle class {
    public static void main(String[] args) throws IOException {
        System.out.println("File Is there:"+f1.exists());
        System.out.println("File Directory:"+f1.isDirectory());
        System.out.println("File Is it a file:"+f1.isFile());
        System.out.println("File Last modified:"+new Date(f1.lastModified()));
        System.out.println("File Size of:"+f1.length());
        System.out.println("File File name:"+f1.getName());
        System.out.println("File Directory path to:"+f1.getPath());


    }
}

6.3 create an empty File or directory through the File object

Delete deletes the specified directory and does not delete the parent directory

7. Enumeration

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

Enum enum name{

Enumerator body (constant list)

}

Enumeration is essentially a class. The enumeration body is to place some constants.

7.1 creating enumeration types

enum Season{
SPRING,SUMMER,AUTUMN,WINTER
}

7.2 use of enumeration

package studyweek4;
import java.util.Random;

public class enumeration {
        public static void main(String[] args){
            //Enumeration traversal
            for(Week k:Week.values()){
                System.out.println(k);
            }
            Week[] ws=Week.values();
            System.out.println(ws[0]);

            //Enumerations used in switch statements
            int a=new Random().nextInt(4);//Generate random numbers of 0, 1, 2 and 3
            switch (Season.values()[a]){  //values() Returns: Week [], which contains all enumeration elements
                case SPRING:
                    System.out.println("spring");
                    break;
                    case SUMMER:System.out.println("summer");
                    break;
                    case AUTUMN:System.out.println("autumn");
                    break;
                    case WINDTER:System.out.println("winter");
                    break;
            }
        }
    }
    /**season*/
    enum Season{SPRING,SUMMER,AUTUMN,WINDTER}
    /**week*/
    enum Week{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}

8. Recursive printing directory tree structure

public class recursion {
    public static void main(String[] args) {
        File f=new File("D:/c++ study");
        printFile(f,0);
    }
    static void printFile(File file, int level){//level is used to add-

        //Output layer times
        for(int i=0;i<level;i++){
            System.out.println("-");
        }

        //Output file name
        System.out.println(file.getName());

        //If file is a directory, get the list of sub files and do the same for each sub file.
        if(file.isDirectory()) {
            File files[] = file.listFiles();//Tree display
            for (File temp : files) {
                //Call this method recursively: pay attention to level+1.
                printFile(temp, level + 1);

            }
        }
    }
}

file.listFiles() is to get the file object, that is, the collection of files and folders under the file directory

Keywords: Java Back-end

Added by ppowell on Sun, 06 Feb 2022 19:42:40 +0200