javaSE -- Java basic class library

1, Java basic class library

Java provides programmers with programming interface API in the form of basic class library JFC (Java Foundation Class). The classes in the class library belong to different packages according to their purposes.

1. Java.lang package

The most commonly used packages of Java belong to this package. Programs do not need to inject this package, they can use the classes in this package, and use these classes to design the most basic Java programs.   

(1) String class, which provides string connection, comparison, character positioning, string printing and other processing methods.   

(2) The StringBuffer class provides further processing methods for strings, including substring processing, character addition and insertion, character replacement, etc.   

(3) System class, which provides reading and writing methods for standard input and output devices io, including keyboard and screen in/out control. The commonly used System.out.print() and System.out.println() are the methods provided by the static variable output stream out of this class

(4) Thread class, which provides Java multithreading processing methods, including thread suspension, sleep, termination and operation.   

(5) Math class, which provides a large number of mathematical calculation methods

(6) . Object class, which is the ancestor class of Java class. This class provides all Java classes with methods to call Java garbage collection Object and methods to wait and wake up based on Object thread safety.

(7) Throwable class, which is the ancestor class of Java error and exception class, and provides methods for Java to handle errors and exceptions.

2. java.awt package

The classes in the package provide methods for creating graphical interfaces, including the establishment and setting of buttons, text boxes, list boxes, containers, fonts, colors, graphics and other elements.

3. javax.swing package

The package provides a graphical interface creation class written in 100%Java. The interface elements established by using the class of the package can be adjusted to the interface style of various operating systems and support the development of interfaces of various operating platforms. In addition, swing package also provides classes for tree control, tab control and table control. Many classes in the Java.swing package are inherited from the classes of the java.awt package. Java retains the java.awt package to maintain technical compatibility, but javax.swing package should be used as much as possible to develop program interfaces.

4. java.io package

The classes of this package provide system input / output control in data flow mode and read / write serialization processing of files and objects. Commonly used classes include BufferInputStream, BufferOutputStream, BufferedReader, BufferedWriter, DataInputStream, DataOutputStream, File, FileReader, FileWriter, FileInputStream and FileOutputStream.

5. java.util package

The package provides classes for creating complex data structures such as time, Date, Random number, list, collection, hash table and stack. The more common classes are Date, Timer, Random and LinkedList.

6. java.net package

The package provides support for network development, including server Serversocket class, client Socket class and URL class for accessing various resources on the Internet.

7. java.applet package

This package has only one Applet class, which is used to develop or embed Applet applets on Web pages, so that web pages have stronger interaction ability, multimedia and network functions.

2, Class libraries that interact with users

1. Parameters for running Java programs

main() method analysis

  • Public modifier: the Java class is called by the JVM. In order for the JVM to call the main() method freely, the public modifier is used to expose this method

  • Static modifier: when the JVM calls this main method, it will not create the object of this class first, and then call the main method through the object. The JVM calls the main method directly through this class, so it modifies the main method with static

  • void return value: because the main method is called by the JVM, the return value of the method will be returned to the JVM, which makes no sense. Therefore, the main() method has no return value

2. Get keyboard input using Scanner

Scanner class can obtain keyboard input. It is a regular expression based text scanner that can parse basic type values and string values from files, input streams and strings

Scanner mainly provides the following two methods to scan input:

  • By default, Scanner uses white space (including keyboard, Tab space, and carriage return) as a separator between multiple entries

  • Scanner uses useDelimiter(String pattern) as the separator setting

Scanner provides the following two methods to read line by line:

public static void main(String[] args){
	// System.in stands for standard input, that is, keyboard input
	Scanner sc = new Scanner(System.in);
	// Add the following line with carriage return as the separator only
	// sc.useDelimiter("\n");
	// Determine whether there is another input item
	while(sc.hasNext()){
		// Output input
		System.out.println("The keyboard input is:" + sc.next());
	}
}

At the same time, Scanner can also read the File input, just pass in the File object as a parameter

public static void main(String[] args)throws Exception{
	// Take a File object as the constructor parameter of Scanner, and Scanner reads the contents of the File
	Scanner sc = new Scanner(new File("ScannerFileTest.java"));
	System.out.println("ScannerFileTest.java The contents of the document are as follows:");
	// Determine if there is a next line
	while(sc.hasNextLine()){
		// Next line in output file
		System.out.println(sc.nextLine());
	}
}

3, System related class libraries

1. System class

The System class represents the running platform of the current Java program. The program cannot create objects of the System class. The System class provides some class variables and class methods, which can be called directly through the System class. You can get the relevant information of the System

public static void main(String[] args) throws Exception{
	// Get all environment variables of the system
	Map<String,String> env = System.getenv();
	for (String name : env.keySet()){
		System.out.println(name + " ---> " + env.get(name));
	}
	// Gets the value of the specified environment variable
	System.out.println(System.getenv("JAVA_HOME"));
	// Get all system properties
	Properties props = System.getProperties();
	// Save all system properties to props.txt file
	props.store(new FileOutputStream("props.txt"), "System Properties");
	// Output specific system properties
	System.out.println(System.getProperty("os.name"));
}
  • System timing methods: currentTimeMillis() (milliseconds) and nanoTime() (nanoseconds), compared with 1970

  • Input and output of System: in, out, err. setInt(), setOut(), setErr() methods are provided

  • The System class provides an identityHashCode(Object x), which returns the exact hash Code value of the specified object. An object can be uniquely identified according to the address of the object

public static void main(String[] args){
	// In the following program, s1 and s2 are two different objects
	String s1 = new String("Hello");
	String s2 = new String("Hello");
	// String rewrites the hashCode() method -- instead, calculate the hashCode value according to the character sequence,
	// Because the character sequences of s1 and s2 are the same, their hashCode method returns the same value
	System.out.println(s1.hashCode() + "----" + s2.hashCode());
	// s1 and s2 are different string objects, so their identityHashCode values are different
	System.out.println(System.identityHashCode(s1) + "----" + System.identityHashCode(s2));
	String s3 = "Java";
	String s4 = "Java";
	// s3 and s4 are the same string objects, so their identityHashCode values are the same
	System.out.println(System.identityHashCode(s3) + "----" + System.identityHashCode(s4));
}

2. Runtime class

The Runtime class represents the Runtime environment of Java programs. Each Java program has a corresponding Runtime instance. An application cannot create its own Runtime instance, but it can get the Runtime object associated with it through the getRuntime() method

Similar to System, Runtime provides gc() and runFinalization(), and load(String filename) and loadLibrary(String libname) to load files and dynamic link libraries

The Runtime can access information about the JVM:

public static void main(String[] args){ // Gets the runtime object associated with the Java program 
    Runtime rt = Runtime.getRuntime(); 
    System.out.println("Number of processors:" + rt.availableProcessors()); 
    System.out.println("Free memory:" + rt.freeMemory()); 
    System.out.println("Total memory:" + rt.totalMemory()); 
    System.out.println("Maximum memory available:" + rt.maxMemory()); 
}

The Runtime can directly start a separate process to run operating system commands

public static void main(String[] args) throws Exception{
	Runtime rt = Runtime.getRuntime();
	// Run Notepad program
	rt.exec("notepad.exe");
}

4, Common class

1. Object class

Object is the parent of all classes, arrays and enumeration classes. That is, Java allows you to assign variables of any type to variables of object type. Object provides the following common methods:

  • boolean equals(Object obj): judge whether the specified object is equal to the object

  • protected void finalize(): when no reference variable in the system refers to the object, the garbage collector calls this method to clean up the resources of the object

  • Class<?> GetClass (): returns the runtime class of the object

  • int hashCode(): returns the hashCode value of the object

  • String toString(): returns the string representation of the object

  • wait(),notify(),notifyAll()

Object also provides a protected modified clone() method to get a copy of the current object, and the two are completely isolated. The steps to realize "self cloning" are as follows:

  • The user-defined class implements the Conable interface, which is a tag line interface without any method defined

  • The custom class implements its own clone() method

  • When implementing the clone() method, use super.clone(); Call the clone () method implemented by Object to get a copy of the Object and return the copy

class Address{
	String detail;
	public Address(String detail){
		this.detail = detail;
	}
}
// Implement clonable interface
class User implements Cloneable{
	int age;
	Address address;
	public User(int age){
		this.age = age;
		address = new Address("Guangzhou Tianhe");
	}
	// The clone() method is implemented by calling super.clone()
	public User clone() throws CloneNotSupportedException{
		return (User)super.clone();
	}
}
public class CloneTest{
	public static void main(String[] args) throws CloneNotSupportedException{
		User u1 = new User(29);
		// clone gets a copy of the u1 object.
		User u2 = u1.clone();
		// Judge whether u1 and u2 are the same
		System.out.println(u1 == u2);      //false
		// Judge whether the address es of u1 and u2 are the same
		System.out.println(u1.address == u2.address);     //true
	}
}

2. New Object class in Java 7

If you are not sure whether an Object is null, using toString() may cause null pointer exception, while toString(Object o) provided by Object will not. If it is null, null string will be returned

// Define an obj variable whose default value is null
static ObjectsTest obj;
public static void main(String[] args)
{
	// Output the hashCode value of a null object and 0
	System.out.println(Objects.hashCode(obj));
	// Output toString of a null object and null
	System.out.println(Objects.toString(obj));
	// It is required that obj cannot be null. If obj is null, an exception will be thrown
	System.out.println(Objects.requireNonNull(obj , "obj Parameter cannot be null!"));
}

3. String, StringBuffer and StringBuilder classes

  • String class is immutable, that is, once a string object is created, the character sequence contained in the object cannot be changed until the object is destroyed.

  • The StringBuffer object represents a String with variable character sequence. After a StringBuffer is created, the character sequence of the String object can be changed through the methods of append(), insert(), reverse(), setCharAt(), setLength(), etc. provided by StringBuffer. Once the final desired String is generated through StringBuffer, its toString() method can be called to convert it into a String object

  • StringBuilder has been used since JDK1.5. It is similar to StringBuffer. The difference is that StringBuffer is thread safe, while StringBuilder is not thread safe and has slightly higher performance. Usually consider the StringBuilder class

4. Math class

Java provides math tools to complete complex operations. Math is a tool class whose constructor modifier is private, so objects cannot be created. Provides a large number of static methods and PI, E

public static void main(String[] args){
	/*---------Here is the trigonometric operation---------*/
	// Convert radians to angles
	System.out.println("Math.toDegrees(1.57): " + Math.toDegrees(1.57));
	// Convert angles to radians
	System.out.println("Math.toRadians(90): " + Math.toRadians(90));
	// Calculates the inverse cosine and returns an angle ranging from 0.0 to pi.
	System.out.println("Math.acos(1.2): " + Math.acos(1.2));
	// Calculate the inverse sine; The returned angle ranges from - pi/2 to pi/2.
	System.out.println("Math.asin(0.8): " + Math.asin(0.8));
	// Calculate arctangent; The returned angle ranges from - pi/2 to pi/2.
	System.out.println("Math.atan(2.3): " + Math.atan(2.3));
	// Calculate the triangular cosine.
	System.out.println("Math.cos(1.57): " + Math.cos(1.57));
	// The hyperbolic cosine of the calculated value.
	System.out.println("Math.cosh(1.2 ): " + Math.cosh(1.2 ));
	// Calculate sine
	System.out.println("Math.sin(1.57 ): " + Math.sin(1.57 ));
	// Calculate hyperbolic sine
	System.out.println("Math.sinh(1.2 ): " + Math.sinh(1.2 ));
	// Calculate trigonometric tangent
	System.out.println("Math.tan(0.8 ): " + Math.tan(0.8 ));
	// Calculate hyperbolic tangent
	System.out.println("Math.tanh(2.1 ): " + Math.tanh(2.1 ));
	// Convert rectangular coordinates (x, y) into polar coordinates (r, thet));
	System.out.println("Math.atan2(0.1, 0.2): " + Math.atan2(0.1, 0.2));
	/*---------Here is the rounding operation---------*/
	// Rounding returns the maximum integer less than the target number.
	System.out.println("Math.floor(-1.2 ): " + Math.floor(-1.2 ));
	// Rounding returns the smallest integer greater than the target number.
	System.out.println("Math.ceil(1.2): " + Math.ceil(1.2));
	// Rounding
	System.out.println("Math.round(2.3 ): " + Math.round(2.3 ));
	/*---------The following are power, square and exponential operations---------*/
	// Calculate the square root.
	System.out.println("Math.sqrt(2.3 ): " + Math.sqrt(2.3 ));
	// Calculate the cube root.
	System.out.println("Math.cbrt(9): " + Math.cbrt(9));
	// Returns the n-th power of Euler number e.
	System.out.println("Math.exp(2): " + Math.exp(2));
	// Return sqrt(x2 +y2)
	System.out.println("Math.hypot(4 , 4): " + Math.hypot(4 , 4));
	// The remainder of the two parameters is calculated according to the provisions of IEEE 754 standard.
	System.out.println("Math.IEEEremainder(5 , 2): " + Math.IEEEremainder(5 , 2));
	// Calculate power
	System.out.println("Math.pow(3, 2): " + Math.pow(3, 2));
	// Calculate natural logarithm
	System.out.println("Math.log(12): " + Math.log(12));
	// Calculate the logarithm of base 10.
	System.out.println("Math.log10(9): " + Math.log10(9));
	// Returns the natural logarithm of the sum of parameter and 1.
	System.out.println("Math.log1p(9): " + Math.log1p(9));
	/*---------The following are symbol related operations---------*/
	// Calculate the absolute value.
	System.out.println("Math.abs(-4.5): " + Math.abs(-4.5));
	// Symbol assignment returns the first floating-point parameter with the second floating-point symbol.
	System.out.println("Math.copySign(1.2, -1.0): " + Math.copySign(1.2, -1.0));
	// Symbolic function; If the parameter is 0, 0 is returned; If the parameter is greater than 0,
	// Returns 1.0; If the parameter is less than 0, - 1.0 is returned.
	System.out.println("Math.signum(2.3): " + Math.signum(2.3));
	/*---------Here are the size dependent operations---------*/
	// Find the maximum
	System.out.println("Math.max(2.3 , 4.5): " + Math.max(2.3 , 4.5));
	// Calculate minimum
	System.out.println("Math.min(1.2 , 3.4): " + Math.min(1.2 , 3.4));
	// Returns the floating-point number adjacent to the first parameter between the first parameter and the second parameter.
	System.out.println("Math.nextAfter(1.2, 1.0): " + Math.nextAfter(1.2, 1.0));
	// Returns a floating point number slightly larger than the target number
	System.out.println("Math.nextUp(1.2 ): " + Math.nextUp(1.2 ));
	// Returns a pseudo-random number greater than or equal to 0.0 and less than 1.0.
	System.out.println("Math.random(): " + Math.random());
}

5. ThreadLocalRandom and Random in Java 7

ThreadLocalRandom class is a new class in Java 7 and an enhanced version of Random. In the environment of concurrent access, using ThreadLocalRandom instead of Random can reduce thread resource competition and finally ensure better thread safety of the system. Similar to Random usage. A static current() method is provided to obtain the ThreadLocalRandom object. After obtaining the object, various nextXxx() methods can be called to obtain the pseudo-Random number

ThreadLocalRandom and Random provide more ways to generate various pseudo-Random numbers than Math's random() method. They can generate floating-point pseudo-Random numbers or integer pseudo-Random numbers, and specify the range of generating Random numbers

Random class is specially used to generate a pseudo-random number. It has two constructors: one constructor uses the default seed (taking the current time as the seed), and the other constructor explicitly passes in the seed of a long integer

public static void main(String[] args){
	Random rand = new Random();
	System.out.println("rand.nextBoolean(): " + rand.nextBoolean());
	byte[] buffer = new byte[16];
	rand.nextBytes(buffer);
	System.out.println(Arrays.toString(buffer));
	// Generate pseudo-random double numbers between 0.0 and 1.0
	System.out.println("rand.nextDouble(): " + rand.nextDouble());
	// Generate pseudo-random float numbers between 0.0 and 1.0
	System.out.println("rand.nextFloat(): " + rand.nextFloat());
	// A pseudo Gaussian number with an average of 0.0 and a standard deviation of 1.0 is generated
	System.out.println("rand.nextGaussian(): " + rand.nextGaussian());
	// Generate a pseudo-random integer in the value range of int integer
	System.out.println("rand.nextInt(): " + rand.nextInt());
	// Generate pseudo-random integers between 0 and 26
	System.out.println("rand.nextInt(26): " + rand.nextInt(26));
	// Generate a pseudo-random integer in the value range of long integer
	System.out.println("rand.nextLong(): " +  rand.nextLong());
}

Generally, use time as seed Random rand = new Random(System.currentTimeMillis());

ThreadLocalRandom usage example:

ThreadLocalRandom rand = ThreadLocalRandom.current();
//Generate a pseudo-random number between 4 and 20
int val1 = rand.nextInt(4,20);
//Generate a pseudo-random number of 2.0 ~ 10.0
int val2 = rand.nextDouble(2.0,10.0);

6. BigDecimal class

For the accurate calculation of floating-point numbers, use String instead of double

public static void main(String[] args){
	BigDecimal f1 = new BigDecimal("0.05");
	BigDecimal f2 = BigDecimal.valueOf(0.01);
	BigDecimal f3 = new BigDecimal(0.05);
	System.out.println("use String As BigDecimal Constructor parameters:");
	System.out.println("0.05 + 0.01 = " + f1.add(f2));
	System.out.println("0.05 - 0.01 = " + f1.subtract(f2));
	System.out.println("0.05 * 0.01 = " + f1.multiply(f2));
	System.out.println("0.05 / 0.01 = " + f1.divide(f2));
	System.out.println("use double As BigDecimal Constructor parameters:");
	System.out.println("0.05 + 0.01 = " + f3.add(f2));
	System.out.println("0.05 - 0.01 = " + f3.subtract(f2));
	System.out.println("0.05 * 0.01 = " + f3.multiply(f2));
	System.out.println("0.05 / 0.01 = " + f3.divide(f2));
}

code:

public class Arith{
	// Default division precision
	private static final int DEF_DIV_SCALE = 10;
	// Constructor private, so that this class cannot be instantiated
	private Arith()	{}
	// Provides accurate addition operations.
	public static double add(double v1,double v2){
		BigDecimal b1 = BigDecimal.valueOf(v1);
		BigDecimal b2 = BigDecimal.valueOf(v2);
		return b1.add(b2).doubleValue();
	}
	// Provides accurate subtraction.
	public static double sub(double v1,double v2){
		BigDecimal b1 = BigDecimal.valueOf(v1);
		BigDecimal b2 = BigDecimal.valueOf(v2);
		return b1.subtract(b2).doubleValue();
	}
	// Provides accurate multiplication.
	public static double mul(double v1,double v2){
		BigDecimal b1 = BigDecimal.valueOf(v1);
		BigDecimal b2 = BigDecimal.valueOf(v2);
		return b1.multiply(b2).doubleValue();
	}
	// Provides (relatively) accurate division operations when inexhaustible division occurs
	// Figures to the nearest 10 decimal places are rounded off.
	public static double div(double v1,double v2){
		BigDecimal b1 = BigDecimal.valueOf(v1);
		BigDecimal b2 = BigDecimal.valueOf(v2);
		return b1.divide(b2 , DEF_DIV_SCALE, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	public static void main(String[] args){
		System.out.println("0.05 + 0.01 = " + Arith.add(0.05 , 0.01));
		System.out.println("1.0 - 0.42 = " + Arith.sub(1.0 , 0.42));
		System.out.println("4.015 * 100 = " + Arith.mul(4.015 , 100));
		System.out.println("123.3 / 100 = " + Arith.div(123.3 , 100));
	}
}

5, Date and schedule of Java 8

1. Date class (use as little as possible)

Java provides a date class to handle time and date. Date contains both date and time

Date provides six constructors, four of which are no longer recommended. The remaining two are as follows:

  • Date(): generate a date object representing the current date and time. The constructor's bottom layer calls System.currentTimeMillis() to obtain a long integer as the date parameter

  • Date(long date): generates a date object according to the specified long integer

Most methods of Date are no longer recommended

    • boolean after(Date when): test whether the date is after the specified date when

    • boolean before(Date when): test whether the date is before the specified date when

    • long getTime(): returns the long type integer corresponding to the time

    • void setTime(long time): sets the time of the Date object

public static void main(String[] args){
	Date d1 = new Date();
	// Get the time 100ms after the current time
	Date d2 = new Date(System.currentTimeMillis() + 100);
	System.out.println(d2);
	System.out.println(d1.compareTo(d2));
	System.out.println(d1.before(d2));
}

2. Calendar Class

In order to make up for the defects in the design of Date, Java provides the Calendar class

Calendar is an abstract class, so you cannot create a calendar object with a constructor. However, several static getInstance() methods are provided to obtain the calendar object. These methods obtain the specific calendar according to the TimeZone and Locale classes. If TimeZone and Locale are not specified, the default TimeZone and Locale are used to create calendar

//Create a default Calendar object
Calendar calendar = Calendar.getInstance();
//Take the Date object from the Calendar object
Date date = calendar.getTime();
//Get the corresponding Calendar object through the Date object
//Because Calendar/GregorianCalendar has no constructor method to receive Date objects
//So you must get a Calendar instance first, and then call its setTime() method
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date);

Calendar provides a number of methods to access and modify dates and times:

  • void add(int field,int amount): adds or subtracts the specified amount of time for a given calendar field according to calendar rules

  • int get(int field): returns the value of the specified calendar field

  • int getActualMaximum(int field): returns the maximum value that the specified calendar field may have

  • int getActualMinimum(int field): returns the minimum value that the specified calendar field may have

  • void roll(int field,int amount): similar to the add() method, except that when the amount exceeds the maximum range that the field can represent, it will not carry forward to the previous field

  • Void set (int file, int value): set the given calendar field to the given value

  • Void set (int file D, int month, int date): sets the values of the year, month, and day fields of the calender object

  • Void set (int year, int month, int date, int hourfday, int minute, int second): sets the values of the year, month, day, hour, minute and second fields of the Calendar object

public static void main(String[] args){
	Calendar c = Calendar.getInstance();
	// Take out year
	System.out.println(c.get(YEAR));
	// Take out the month
	System.out.println(c.get(MONTH));
	// Withdrawal day
	System.out.println(c.get(DATE));
	// Set year, month, day, hour, minute and second respectively
	c.set(2003 , 10 , 23 , 12, 32, 23); //2003-11-23 12:32:23
	System.out.println(c.getTime());
	// Push Calendar forward by 1 year
	c.add(YEAR , -1); //2002-11-23 12:32:23
	System.out.println(c.getTime());
	// Push Calendar forward by 8 months
	c.roll(MONTH , -8); //2002-03-23 12:32:23
	System.out.println(c.getTime());
}

The difference between add and roll

  • add(int field,int amount) is mainly used to change the value of a specific field of Calendar. If you want to increase, amount is a positive number and decrease is a negative number

    • When the modified field exceeds its allowable range, carry will occur, that is, the upper level field will also increase.

Calendar cal1 = Calendar.getInstance();
cal1.set(2003, 7, 23, 0, 0 , 0); // 2003-8-23
cal1.add(MONTH, 6); //2003-8-23 => 2004-2-23
System.out.println(cal1.getTime());
  • If the next field also needs to be changed, the field will be corrected to the value with the smallest change

Calendar cal2 = Calendar.getInstance();
cal2.set(2003, 7, 31, 0, 0 , 0); // 2003-8-31
// Since the carry in month is changed to February, February does not have 31 days and automatically becomes 29 days
cal2.add(MONTH, 6); // 2003-8-31 => 2004-2-29
System.out.println(cal2.getTime());

The processing rules of roll() and add() are different:

  • When the modified field exceeds its allowable range, the upper level will not increase.

Calendar cal3 = Calendar.getInstance(); 
cal3.set(2003, 7, 23, 0, 0 , 0); //2003-8-23 / / the month field is "carry", but the YEAR field is not increased 
cal3.roll(MONTH, 6); //2003-8-23 => 2003-2-23 
System.out.println(cal3.getTime());
  • The processing rules of the next level fields are similar to add()

Calendar cal4 = Calendar.getInstance();
cal4.set(2003, 7, 31, 0, 0 , 0); //2003-8-31
// After the "carry" of the MONTH field, it becomes 2. There is no 31 February,
// The YEAR field will not change. There are only 28 days in February 2003
cal4.roll(MONTH, 6); //2003-8-31 => 2003-2-28
System.out.println(cal4.getTime());

Set calendar compatibility

  • When an illegal parameter setting value is passed in, setLenient(false) can be used to turn off fault tolerance and allow it to conduct strict parameter checking

public static void main(String[] args){
	Calendar cal = Calendar.getInstance();
	// The result is the YEAR field plus 1 and the MONTH field is 1 (February)
	cal.set(MONTH , 13);   //①
	System.out.println(cal.getTime());
	// Turn off fault tolerance
	cal.setLenient(false);
	// Cause runtime exception
	cal.set(MONTH , 13);   //②
	System.out.println(cal.getTime());
}

The set() method delays modification

  • The set(f,value) method changes the Calendar field f to value, and sets an internal member variable to indicate that the Calendar field f has been changed. f is changed immediately, but the time represented by the Calendar will not be modified immediately. The Calendar time will not be recalculated until get(), getTime(), getTimeInMillis(), add() or roll() is called next time. This is called a deferred modification of the set () method. There will be no multiple calculations due to multiple calls to set()

public static void main(String[] args){
	Calendar cal = Calendar.getInstance();
	cal.set(2003 , 7 , 31);  //2003-8-31
	// The month is set to 9, but September 31 does not exist.
	// If you modify it immediately, the system will automatically adjust cal to October 1.
	cal.set(MONTH , 8);
	// The following code outputs October 1
	//System.out.println(cal.getTime());     // Do not make it effective
	// Set the DATE field to 5
	cal.set(DATE , 5);    //②
	System.out.println(cal.getTime());    //2003-9-5
}

6, New date and time package in Java 8

Java 8 has added a java.time package, which contains the following common classes:

  • Clock: used to obtain the current date and time of the specified time zone

  • Duration: represents the duration

  • Instant: represents an accurate moment, which can be accurate to nanoseconds. Static method new(),new(Clock clock),minusXxx(),plusXxx()

  • LocalDate: represents the date without time zone. Static method new(),new(Clock clock),minusXxx(),plusXxx()

  • LocalTime: represents the time without time zone. Static method new(),new(Clock clock),minusXxx(),plusXxx()

  • LocalDateTime: represents the date and time without time zone. Static method new(),new(Clock clock),minusXxx(),plusXxx()

  • MonthDay: only represents month day. Static method new(), new (clock)

  • Year: only represents the year. Static method new(),new(Clock clock),minusYears(),plusYears()

  • YearMonth: only represents month and year. Static method new(),new(Clock clock),minusXxx(),plusXxx()

  • ZonedDateTime: represents a time zone date and time

  • ZoneId: represents a time zone

  • DayOfWeek: defines the enumeration class from Sunday to Saturday

  • Month: defines the enumeration class from January to December

7, Regular expression

Regular expression is a powerful String processing tool, which can find, extract, segment and replace strings. The String class also provides the following special methods:

  • boolean matches(String regex): judge whether the string matches the specified regular expression

  • String replaceAll(String regex,String replacement): replace all substrings matching regex in the string with replacement

  • String replaceFirst(String regex,String replacement): replace the first substring matching regex in the string with replacement

1. Create regular expressions

  • Creating a regular expression is essentially creating a special string.

  • Regular expressions support the following legal characters, as well as some special characters

x

Character x (x can represent any legal character)

\0mnn

Character represented by octal number 0mnn

\xhh

The number represented by the hexadecimal value 0xhh

\uhhhh

Unicode character represented by hex value 0xhhhh

\t

Tab ('\ u0009')

\n

New line (newline) character ('\ u000A')

\r

Carriage return ('\ u000D')

\f

Page feed ('\ u000C')

\a

Alarm (bell) character ('\ u0007')

\e

Escape character ('\ u001B')

\cx

Control character corresponding to x (e.g \cM matches Ctrl+M)

$

Match the end of a line

\$

^

Match the beginning of a line

\^

(&emsp;)

Mark the start and end positions of the subexpression

\(&emsp;\)

[&emsp;]

Used to determine the start and end positions of bracket expressions

\[&emsp;\]

{&emsp;}

Used to mark the frequency of occurrence of the front sub expression

\{&emsp;\}

*

Specifies that the front sub expression can appear zero or more times

\*

+

Specifies that the front sub expression can appear one or more times

\+

?

Specifies that the front sub expression can appear zero or once

\?

.

Matches any single character except the newline character \ n

\.

\\

Used to escape the next character or specify octal or hexadecimal characters

\\

|

Specify either one of the two

|

Concatenate the above characters to create a regular expression.

e.g:

"\ u0041 \ \" / / match A\

"\ u0061\t" / / match a < tab >

"\? \ [" / / match[

The above regular expressions can only match a single character. Regular expressions also have wildcards, that is, predefined characters, which are used to match multiple characters

.

Can match any character

\d

Match all numbers from 0 to 9

\D

Match non numeric

\s

Match all white space characters, including space, tab, carriage return, page feed, line feed, etc

\S

Match all non whitespace characters

\w

Match all word characters, including 0 ~ 9 all numbers, 26 English letters and underscores ()

\W

Match all non word characters

  • Memory tips: d-digit, for numbers. s-space, for blanks. w-word, for words

Expressions that are more powerful than before are created

e.g:

c\wt / / a batch of strings such as cat, CBT, CCT, c0t and c9t can be matched \ D \ D \ D - \ D \ D - \ D \ D \ D / / phone numbers in the form of 000-000-0000 can be matched

In order to match alphabetic and non alphabetic segments, square bracket expressions need to be applied

Represents an enumeration

[abc] represents any one of a, b and c

Representation range:-

[a-d] represents any character in the ad range, which can be used with enumeration, ` [a-fx-z] ` represents any character in the af and x-z ranges

Indicates whether or not:^

[^ abc] represents any character other than a, b and c, and [^ a-f] represents any character other than a~f

Represents an and operation:&&

[A-Z & & [def] represents the intersection of a~z and [def], represents d, e or f, and [A-Z & & [^ BC]] is [ad-z]

Represents a union operation

Parallel operation is similar to enumeration, [a-d[m-p]] is [a-dm-p]

Parenthesis expression: used to form multiple expressions into a sub expression. The or operator (|) e.g."((a)|(b)|(c))" can be used in parentheses

Boundary match

^

Start of line

$

End of line

\b

Word boundaries

\B

Non word boundaries

\A

Start of input

\G

End of previous match

\Z

The end of the input, only for the last terminator

\z

End of input

Quantity identifier of regular expression, Greedy pattern: always match. Reluctant pattern is represented by question mark suffix (?) and will only match the least characters. Possessive pattern is represented by plus sign suffix (+)

2. Using regular expressions

  • Once the regular expression is defined in the program, you can use pattern and Matcher to use the regular expression. The pattern object is the representation of the regular expression in memory after compilation, so the regular expression will be compiled into a pattern object first, and then the corresponding Matcher object will be created by using the pattern object. The results involved in matching will be retained in the Matcher object, and multiple matches The Cher object can share the same pattern object. Pattern is an immutable class and can be safely used by multiple concurrent threads. The typical calling sequence is as follows:

//Compile a string into a Pattern object
Pattern p = Pattern.compile("a*b");
//Creating a Matcher object using a Pattern object
Matcher m = p.matcher("aaaaab");
boolean b = m.matches(); //Return true

The Pattern object defined above can be reused many times. If it is used only once, you can call the static method matcher() of the Pattern class

boolean b = Pattern.matches("a*b","aaaaab"); //Return true

Matcher class provides the following common methods:

  • find(): Returns whether the target string contains a string matching the Pattern

  • find(int i): search down from index I to return whether the target string contains a string matching Pattern

  • group(): returns the last string matching Pattern

  • start(): returns the start position of the string matching Pattern last time in the target string

  • end(): returns the end position of the last string matching Pattern in the target string + 1

  • lookingAt(): Returns whether the front part of the target string matches the Pattern

  • matches(): Returns whether the entire target string matches the Pattern

  • reset(): applies an existing Matcher object to a new character sequence

public class FindGroup{
	public static void main(String[] args){
		// Use string simulation to get the web page source code from the network
		String str = "I want to buy a copy of crazy Java Handout ", contact me as soon as possible 13500006666"
			+ "Make friends. The phone number is 13611125565"
			+ "Sale of second-hand computers, contact 15899903312";
		// Create a Pattern object and use it to create a Matcher object
		// The regular expression only captures the mobile phone numbers of 13X and 15X segments,
		// What phone numbers do you actually want to grab? Just modify the regular expression.
		Matcher m = Pattern.compile("((13\\d)|(15\\d))\\d{8}").matcher(str);
		// All substrings (phone numbers) conforming to regular expressions are output
		while(m.find()){
			System.out.println(m.group());
		}
	}
}

public class StartEnd{
	public static void main(String[] args){
		// Create a Pattern object and use it to create a Matcher object
		String regStr = "Java is very easy!";
		System.out.println("The target string is:" + regStr);
		Matcher m = Pattern.compile("\\w+").matcher(regStr);
		while(m.find()){
			System.out.println(m.group() + "Start position of substring:"+ m.start() + ",Its end position:" + m.end());
		}
	}
}

public class MatchesTest{
	public static void main(String[] args){
		String[] mails ={
			"kongyeeku@163.com" ,
			"kongyeeku@gmail.com",
			"ligang@crazyit.org",
			"wawa@abc.xx"};
		String mailRegEx = "\\w{3,20}@\\w+\\.(com|org|cn|net|gov)";
		Pattern mailPattern = Pattern.compile(mailRegEx);
		Matcher matcher = null;
		for (String mail : mails){
			if (matcher == null){
				matcher = mailPattern.matcher(mail);
			}else{
				matcher.reset(mail);
			}
			String result = mail + (matcher.matches() ? "yes" : "no")+ "A valid email address!";
			System.out.println(result);
		}
	}
}

8, Automatic disassembly box

(1) . automatic packing

Convert basic data type to wrapper type

(2) . automatic unpacking

Convert wrapper type to basic data type

//Automatic packing
Integer total = 99;
//Automatic unpacking
int totalprim = total;

Keywords: Java Back-end JavaSE

Added by phui_99 on Mon, 01 Nov 2021 06:33:28 +0200