java introduction notes 8

Keyword learning

static keyword

In a class, member variables declared with static are static member variables, also known as class variables. Class variables have the same life cycle as classes and are valid throughout the execution of the application. It has the following characteristics:

  • It is a public variable of this class and belongs to a class. It is shared by all instances of this class and is explicitly initialized when the class is loaded
  • For all objects of this class, there is only one static member variable. Shared by all objects of this class
  • It is generally called with "class name. Class attribute / method". (static members can also be accessed through object references or class names (no instantiation is required)
  • Non static members cannot be accessed directly in static methods
package com.bjsxt;
        public class jj{
            int id;
            String name;
            static String company="Beijing";//City name
            public jj(int id,String name){
                this.id=id;
                this.name=name;
            }
            public void login(){
                System.out.println("Sign in:"+name);
                System.out.println(comanpy);
            }
            public static void printComanpy(){
                //login();// If you call a non static member, the compilation will report an error
                System.out.println(company);
            }
            public static void main(String[] args){
                   jj U=new jj(15,"java");
                   jj.printComanpy();
        }
    }

The method area stores static variables, classes, or static.

  • Non static can call static
  • Static cannot call non static

Static initialization block

Construction method is used for object initialization! Static initialization block, used for class initialization operation! Non static members cannot be accessed directly in static initialization blocks.

package com.bjsxt;
        public class jj{
            int id;
            String name;
            String pwd;
            static String company="Beijing o";//City name
            static { 
                     //Ordinary properties and methods cannot be called
                     //Because there is no object for class initialization
                     //If there is a constructor, execute static first and construct the class first.
                System.out.println("Perform class initialization");
                company="bf";
                printComanpy();
            }
            public static void printComanpy(){
                System.out.println(company);
            }
        public static void main(String[] args){
		           jj u3=null;
        }
    }

Time processing related classes

We use long type variables to represent time, which can be expressed hundreds of millions of years from the base time to the next hundreds of millions of years. If you want to get the "time value" of the current time, you can use:

  • long now=System.currentTimeMillis();

Date time class (java.util.Date)

package com.bjsxt;
import java.util.Date;
        public class jj{
            public static void main(String[] args) {
               /** //Integer.MIN_VALUE
                long a=Long.MAX_VALUE/(1000L*3600*24*365);//Long.MAX_VALUE Maximum value, plus L to prevent overflow
                System.out.println(a);//About 290 million years later

                long nowNum=System.currentTimeMillis();//Represents the number of milliseconds at the current time
                System.out.println(nowNum);*/

                Date a1=new Date();//If there is no parameter, it represents the current time
                System.out.println(a1);
                System.out.println(a1.getTime());//Returns the number of milliseconds of the current time

                Date a2=new Date(1000L*3600*24*365*250);
                System.out.println(a2);//
                
            }
    }

DateFomat class and SlimpleDateFormat class

  • Function of DateFomat class
    Converts the time object into a string in the specified format. On the contrary, the string in the specified format is converted into a time object.
    DateFomat is an abstract class, which is generally implemented by its subclass SimpleDateFormat class.
package com.bjsxt;
/**
 * Test the mutual conversion of time object and string
 * Use: DateFormat, SimpleDateFormat
 * */
import java.text.DateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Spliterators;
import java.util.function.LongConsumer;
public class jj{
            public static void main(String[] args) throws ParseException {
                //new output SimpleDateFormat object
                // SimpleDateFormat s1=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                SimpleDateFormat s1=new SimpleDateFormat("yyyy year MM month dd day hh Time mm branch ss second");

                //Convert string to Date object
               // Date d1=s1.parse("1971-3-10 10:40:52");
                Date d1=s1.parse("1971 10:40:52 on March 10");
                System.out.println(d1.getTime());

                //Converts a Date object to a string
                Date d2=new Date();
                String str=s1.format(d2);
                System.out.println(str);

                DateFormat df2=new SimpleDateFormat("The first of this year w week,The first of this year D day");
                System.out.println(df2.format(d2));
                //Note: convert the string conforming to the specified format into a time object. The string format needs to be consistent with the specified format.

            }
}

Calendar Class

Calendar class is an abstract class, which provides us with relevant functions of date calculation, such as display and calculation of year, month, day, hour, minute and second.
Gregorian Calendar is a specific subclass of Calendar, which provides the standard Calendar system used in most countries in the world.

  • Note the representation of month. JANUARY is 0, February is 1, and so on. December is 11 Because most people are used to using words instead of numbers to represent months, the program may be easier to read. The parent class Calendar uses constants to represent months: JANUARY, etc

Use of GregorianCalendar class and Calendar Class

package com.bjsxt;
import java.util.*;
public class jj{
            public static void main(String[] args) {
                //Get date related elements
                GregorianCalendar calendar=new GregorianCalendar(2999,10,9,22,10,50);
                int year=calendar.get(Calendar.YEAR);//Print 1999
                int month=calendar.get(Calendar.MONTH);//Print 10
                int day=calendar.get(Calendar.DAY_OF_MONTH);//Print 9
                int day2=calendar.get(Calendar.DATE);//Print 9
                //Day: calendar Month and calendar DAY_ OF_ Month synonym
                int date=calendar.get(Calendar.DAY_OF_WEEK);//Print 3
                //The day of the week, here is: 1-7. Sunday is 1, Monday is 2... Saturday is 7
                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,2999);
                calendar2.set(Calendar.MONTH,Calendar.FEBRUARY);
                calendar2.set(Calendar.DATE,3);
                calendar2.set(Calendar.HOUR_OF_DAY,10);
                calendar2.set(Calendar.MINUTE,20);
                calendar2.set(Calendar.SECOND,23);
                printCalendar(calendar2);
                //Date calculation
                GregorianCalendar calendar1=new GregorianCalendar(2999,10,9,22,10,50);
                calendar1.add(Calendar.MONTH,-7);//Decrease in July
                calendar1.add(Calendar.DATE,7);//Add 7 days
                printCalendar(calendar1);
                //Calendar object and time object conversion
                Date d=calendar1.getTime();
                GregorianCalendar calendar3=new GregorianCalendar();
                calendar3.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 Sunday, Sunday%s %d:%d:%d\n",year,month,day,week,hour,minute,second);
            }
}

Other common classes

Math class

Common methods of Math class

package com.bjsxt;
public class jj {
    public static void main(String[] args) {
    //Rounding related operations
        System.out.println(Math.ceil(3.2));
        System.out.println(Math.floor(3.2));
        System.out.println(Math.round(3.2));
        System.out.println(Math.round(3.2));
    //Absolute value, square root, b-th idempotent operation of a
        System.out.println(Math.abs(-6));
        System.out.println(Math.sqrt(9));
        System.out.println(Math.pow(5,2));
        System.out.println(Math.pow(2,5));
    //Constants commonly used by Math class
        System.out.println(Math.PI);
        System.out.println(Math.E);
    //random number
        System.out.println(Math.random());//[0,1];
    }
}

Random class

package com.bjsxt;
import java.util.Random;
public class jj {
    public static void main(String[] args) {
        Random rand=new Random();
        //Randomly generate double type data between (0, 1)
        System.out.println(rand.nextDouble());
        //Randomly generate integer data within the allowable range of int type
        System.out.println(rand.nextInt());
        //Randomly generate float type data between (0, 1)
        System.out.println(rand.nextFloat());
        //Generate false or true randomly
        System.out.println(rand.nextBoolean());
        //Randomly generate int type data between [0,10]
        System.out.print(rand.nextInt(10) );
        //Randomly generate int type data between [20,30]
        System.out.print(20+rand.nextInt(10));
        //Randomly generate int type data between [20,30] (this calculation method is more complex)
        System.out.print(20+(int)(rand.nextDouble()*10));
    }
}

File class

The File class is used to represent files and directories.

  • java.io.File class: represents files and directories.
package com.bjsxt;

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

public class jj {
    public static void main(String[] args) throws IOException {
       /**
       File Class creation file
       */
       File f1=new File("d:/movies/Kung Fu Panda.mp4");//create a file
       // File f1=new File("d:\movie \ \ / Kung Fu Panda. mp4");
       File f2=new File("d:/movies");//Create directory

       System.out.println(System.getProperty("user.dir"));//Get the path of the project
        File f3=new File(System.getProperty("user.dir"));
       /**
       Use the File class to access File or directory properties
       */
        f1.createNewFile();
        //Thrown out in case of exception
        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());
    }
}
methodexplain
public boolean exists()Determine whether the File exists
public boolean isDirectory()Determine whether File is a directory
public boolean isFile()Determine whether File is a File
public boolean lastModified()Return to the last modification time of File
public boolean length()Returns the size of the File
public boolean getName()Returns the File name of the File
public boolean getPath()Returns the directory path of the File
  • Create an empty File or directory through the File object (if the File or directory referred to by the object does not exist)
methodexplain
creatNewFile()Create a new File
delete()Delete the File corresponding to File
mkdir()Create a directory; If a directory in the middle is missing, the creation fails
mkdirs()Create multiple directories; If a directory in the middle is missing, the missing directory is created
File f4=new File("D:/movies/mainland/study/programming/Shang Xuetang/Gao Qi");
        File f5=new File("D:/movies/programming/Shang Xuetang/Gao Qi");
        boolean flag1=f4.mkdirs();//It doesn't matter if one of the directory structures doesn't exist; Create the entire directory tree
        boolean flag2=f5.mkdir();//If one of the directory structures does not exist, the entire directory tree will not be created
        System.out.println(flag1);//true, successfully created
        System.out.println(flag2);//false, creation failed
        //    f4.delete();f4 contains the "high flag" directory. Only delete the target directory, otherwise disk D will be gone

enumeration

The definition of enumeration type includes enumeration declaration and enumeration body. The format is as follows:

Enum enum name{
Enumerator body (constant list)}

Create enumeration type

enum Season{
  	SPRING,SUMMER,AUTUMN,WINTER
  	}

All enumeration types implicitly inherit from Java lang.Enum. Enumeration is essentially a class! Each enumerated member is essentially an instance of an enumerated type. By default, they are decorated with public static final. You can use them directly by enumerating type names.
Use of enumerations

package com.bjsxt;
import java.util.Random;
public class St {
    public static void main(String[] args) {
        //Enumeration traversal
        for(Week k:Week.values()){
            //values() returns: Week [] contains all enumeration elements, which is an array enhancement loop
            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]){
            //Season.values()[a]
            case SPRING:
                System.out.println("spring");
                break;
            case SUMMER:
                System.out.println("summer");
                break;
            case AUTUMN:
                System.out.println("autumn");
                break;
            case WINTER:
                System.out.println("winter");
                break;
        }
    }
    /**
     * public static final int SPRING=0;
     * public static final int SUMMER=1;
     * public static final int AUTUMN=2;
     * public static final int WINTER=3;
     */
    enum Season{
        SPRING,SUMMER,AUTUMN,WINTER
    }
    enum Week{
        Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
    }
}

Keywords: Java Back-end

Added by Xorandnotor on Sun, 20 Feb 2022 20:26:00 +0200