Java review notes - Commonly used APIs


1. API Overview

Java API is a collection of classes and interfaces provided by the Java language for developing Java applications. It contains various functional modules, such as graphical interface, network communication, database access, multi-threading, file operations, etc., as well as some commonly used data structures and algorithms.

The design goal of the Java API is to provide a set of reliable, efficient, and easy-to-use tools and functions to help developers build applications more quickly. It provides a wealth of classes and interfaces, and developers can choose and use these APIs according to their own needs.

Java API is divided into multiple packages according to functions, such as java.lang, java.util, java.io, etc. Each package contains a set of related classes and interfaces to facilitate modular development and code reuse by developers.

Using Java API can greatly simplify the development process. Developers do not need to design and implement various functions from scratch, but can directly use the classes and methods provided by the API. At the same time, the Java API also provides documentation and sample code to facilitate developers to learn and use.

In short, the Java API is the core part of the Java language, providing a wealth of tools and functions to help developers develop Java applications more efficiently.

2. Math

(1) Overview of Math

The Math class in Java is a utility class that contains mathematical operation methods. It provides many static methods for performing common mathematical operations. The following are some common Math class methods:

  1. abs(): Returns the absolute value of a number.
  2. ceil(): Round up.
  3. floor(): round down.
  4. round(): round to an integer.
  5. max(): Returns the larger of the two numbers.
  6. min(): Returns the smaller of the two numbers.
  7. pow(): Returns the specified power of a number.
  8. sqrt(): Returns the square root of a number.
  9. random(): Returns a random number between 0 and 1.
  10. sin(), cos(), tan(): trigonometric functions.
  11. log(), log10(): logarithmic function.

To use a method of the Math class, just add the class name "Math." before the method name, for example:

int absoluteValue = Math.abs(-5);
double roundedValue = Math.round(2.6);
double randomValue = Math.random();

More details about the Math class and how to use other methods can be found in the official Java documentation.

(2) Math practice

1. Prime number judgment

Requirement: Determine whether a number is prime and use the square root optimization algorithm.

To determine whether a number is prime, you can use the square root optimization algorithm. The basic idea of ​​the square root optimization algorithm is that for a number n, if there is a factor p such that p * q = n, then there must be a square root less than or equal to n in p and q. Therefore, you only need to determine whether there is a factor of n between 2 and the square root n.

The following is an example code that uses the square root optimization algorithm to determine whether a number is prime:

public class PrimeNumberChecker {
    
    
    public static boolean isPrime(int number) {
    
    
        if (number <= 1) {
    
    
            return false;
        }
        
        // 判断在2到平方根number之间是否存在number的因子
        for (int i = 2; i <= Math.sqrt(number); i++) {
    
    
            if (number % i == 0) {
    
    
                return false;
            }
        }
        
        return true;
    }
    
    public static void main(String[] args) {
    
    
        int number = 17;
        if (isPrime(number)) {
    
    
            System.out.println(number + " is a prime number.");
        } else {
    
    
            System.out.println(number + " is not a prime number.");
        }
    }
}

In the above code, the isPrime() method receives an integer as a parameter to determine whether the number is prime. If the number is less than or equal to 1, return false directly. Then use the square root optimization algorithm to determine whether there is a factor of number between 2 and the square root number. If it exists, return false; otherwise, return true.

In the main() method, we pass in a number 17 for testing. After running the code, "17 is a prime number." will be output, indicating that 17 is a prime number.

You can call the isPrime() method as needed to determine whether different numbers are prime.

2. Number of daffodils

Explanation: From exponentiation, an n-digit natural number is equal to the sum of the n-th power of the numbers in each of its digits.
Example 1 (three-digit number is also called the daffodil number): 1^3 + 5^3 + 3^3 = 153
Example 2 (four-digit number is also called the four-leaf rose number): 1^4 + 6^4 + 3^4 + 4^3 = 1634
Requirement: Count how many daffodils there are in total.

The daffodil number refers to an n-digit positive integer, the sum of the nth power of its digits is equal to itself. For example, 153 is a daffodil number because 1^3 + 5^3 + 3^3 = 153.

Here is a Java program that counts and prints all daffodil numbers between 100 and 999:

public class NarcissisticNumbers {
    
    
    public static void main(String[] args) {
    
    
        for (int i = 100; i <= 999; i++) {
    
    
            if (isNarcissistic(i)) {
    
    
                System.out.println(i);
            }
        }
    }

    public static boolean isNarcissistic(int num) {
    
    
        int original = num;
        int sum = 0;
        int n = String.valueOf(num).length();

        while (num > 0) {
    
    
            int digit = num % 10;
            sum += Math.pow(digit, n);
            num /= 10;
        }

        return sum == original;
    }
}

This program contains two methods: mainand isNarcissistic. mainmethod is used to iterate over all integers between 100 and 999 and call isNarcissisticthe method to check whether each integer is a daffodil number. If so, print it to the console.

isNarcissisticThe method accepts an integer as a parameter and returns a Boolean value indicating whether the integer is a narcissus number. This method first calculates the number of digits in the integer and then uses a loop to add the nth powers of the digits to obtain a sum. Finally, the sum is compared to the original integer and returns true if they are equal, false otherwise.

Three, System

(1) System overview

In the Java programming language, System is a class that represents the system's standard input, output, and error output streams. The System class also contains some information about the running status of the system, such as the name of the current system's default character set.

The System class is part of Java's core class library and contains the following main members:

  1. Standard Input Stream (System.in): This is the primary way that programs get input from the user. In Java, you can use Scanner class to read input from System.in.
  2. Standard Output Stream (System.out): This is the primary way a program displays output to the user. In Java, you can write output to System.out using the System.out.println() or System.out.print() method.
  3. Standard Error Stream (System.err): This is the primary way that programs display error output to the user. In Java, you can write error output to System.err using the System.err.println() or System.err.print() method.
  4. System properties (System.getProperty() and System.setProperty()): These methods are used to get and set properties of the Java system. For example, you can get the name of the operating system through System.getProperty("os.name").

Here is an example of how to use the System class:

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int number = scanner.nextInt();
        System.out.println("你输入的整数是: " + number);
    }
}

In this example, we use System.in as the input source of the Scanner, and then use System.out.println() to print out the integer entered by the user.

(2) Commonly used methods of System

The System class has many commonly used methods that provide access to system-level functions and operations. The following are some commonly used System class methods:

1. currentTimeMills()

currentTimeMillis()Is a static method of Java's System class that returns the current time in milliseconds. It returns the current time, in milliseconds, since January 1, 1970, 0:00:00 (UTC). This method provides a simple and efficient way to obtain the current time.

The following is currentTimeMillis()an example usage of the method:

long currentTime = System.currentTimeMillis();
System.out.println("当前时间(毫秒): " + currentTime);

The output will be similar to:

当前时间(毫秒): 1626838345529

This method is great for recording the running time of an application or the time intervals between performing certain operations.

2. arraycopy(src, srcPos, dest, destPos, length)

arraycopyIt is a static method of Java's System class, used to copy part of the contents of an array to the same position of another array. This method is very efficient because it uses a direct copy of memory under the hood instead of copying element by element through a loop.

Here is arraycopythe signature of the method:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Parameter Description:

  • src: source array
  • srcPos: The starting position of the source array (starting from 0)
  • dest: target array
  • destPos: The starting position of the target array (starting from 0)
  • length: number of elements to copy

This method will copy the elements of srcthe array starting srcPosat and of length lengthto destthe array starting destPosat position .

Here is an example:

int[] source = {
    
    1, 2, 3, 4, 5};
int[] target = new int[5];

System.arraycopy(source, 0, target, 0, 3);

// 此时 target 为 {1, 2, 3, 0, 0}

In the above example, we use arraycopythe method to sourcecopy the first three elements of the array into targetthe array. Notice that targetthe rest of the array is filled with the default value (0 in this case).

3. identityHashCode(Object x)

identityHashCode(Object x)Is a static method of Java's System class that returns the identity hash code of the object. An identity hash code is a unique identifier automatically stored by the system for each object, often used for quick comparison of objects or to store objects in a hash table.

The following is identityHashCode()an example usage of the method:

Object obj = new Object();
int hash = System.identityHashCode(obj);
System.out.println("对象的身份哈希码: " + hash);

The output will be similar to:

对象的身份哈希码: 182317697

NOTE: Identity hash codes are automatically generated by the JVM for each object and therefore should not be used directly by applications. It is mainly used for low-level system-level operations, such as storing objects in hash tables.

4. in

inIt is a static member variable of Java's System class and represents the standard input stream. It is usually used to read user input and can enter data from the keyboard.

Here is insample code for reading user input using :

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一个整数:");
        int num = scanner.nextInt();
        System.out.println("您输入的整数是:" + num);
    }
}

In the above code, we use System.inas Scannerthe input source of , and then read the integer entered by the user through the method Scannerof .nextInt()

NOTE: inIt is read-only and should not be modified. In addition, if you need to read data from other input sources, you can use InputStreaman object of type as Scannerthe input source of .

5. out

outIt is a static member variable of Java's System class and represents the standard output stream. It is usually used to display output to the user, and can output data to the console or a file.

Here is outsample code that displays output using:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("Hello, World!");
    }
}

In the above code, we use System.out.println()the method to output the string "Hello, World!" to the user.

NOTE: outIt is read-only and should not be modified. Additionally, if you need to redirect output to another destination, you can use PrintStreaman object of type as the output stream.

6. err

errIt is a static member variable of Java's System class and represents the standard error stream. It is usually used to display program error messages and can output data to the console or file.

Here is errsample code that displays an error message using:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int result = 1 / 0; // 除以 0 的错误
        System.err.println("Error: Division by zero!");
    }
}

In the above code, we intentionally perform an incorrect calculation of division by 0 and then use System.err.println()the method to output a custom error message to the user.

NOTE: errIt is read-only and should not be modified. Additionally, if you need to redirect error messages to other destinations, you can use PrintStreaman object of type as the error stream.

7. getProperty(String key)

getProperty(String key)Is a static method of Java's System class that returns the system property value associated with the specified key. System properties are part of the Java system runtime environment and can provide information about the Java virtual machine, operating system, user environment, etc.

getProperty()The following is sample code to obtain system properties using the method:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        String javaVersion = System.getProperty("java.version");
        String osName = System.getProperty("os.name");
        String userHome = System.getProperty("user.home");

        System.out.println("Java Version: " + javaVersion);
        System.out.println("Operating System Name: " + osName);
        System.out.println("User Home Directory: " + userHome);
    }
}

In the above code, we use getProperty()the method to obtain the Java version number, operating system name, and system attribute value of the user's home directory respectively, and output them to the console.

Note: getProperty()The method returns a string type result, so you need to pay attention to the parsing and processing of the string when using it. Additionally, if the specified key does not exist in the system property, the method will return null or a default value, depending on the Java version and operating system used.

8. setProperty(String key, String value)

setProperty(String key, String value)Is a static method of Java's System class that sets system properties to specified keys and values. By setting system properties, you can modify the behavior and configuration of the Java system runtime environment.

setProperty()The following is sample code for setting system properties using the method:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        System.setProperty("java.awt.headless", "true"); // 设置系统属性

        // 其他代码
    }
}

In the above code, we setProperty()set the system property named "java.awt.headless" to "true" using the method. This property is used to specify whether the Java application is running in a headless environment, that is, without a graphical user interface. GUI related features can be disabled by setting this property to "true".

Note: setProperty()The system properties set by the method are valid for the current process and its sub-processes. However, when the process ends, system properties may be lost or reset to their default values. If you need to persist system properties, you can consider writing them to a configuration file or using a persistence mechanism such as a database to store them.

9. clearProperty(String key)

clearProperty(String key)It is a static method of Java's System class, used to clear the system properties of the specified key. By clearing a system property, you can delete its corresponding value, thereby restoring the default state or removing a specific configuration.

clearProperty()The following is sample code for clearing system properties using the method:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        System.clearProperty("java.awt.headless"); // 清除系统属性

        // 其他代码
    }
}

In the above code, we use clearProperty()the method to clear the system property named "java.awt.headless". This will delete the property's value, return it to its default state, or remove the specific configuration.

Note: clearProperty()The method clears the system attributes of the current process. If other processes or subprocesses use this attribute, they still retain its value. In addition, after clearing the system property, if you call getProperty()the method again to get the value of the property, it may return null or a default value, depending on the Java version and operating system used.

10. lineSeparator()

lineSeparator()Is a static method of Java's System class, used to return the system line separator. The system line delimiter is a specific sequence of characters used to represent text line breaks. It can be a single character, such as the line feed character ('\n'), or it can be a sequence of multiple characters that represent line breaks, such as the carriage return and line feed character in Windows systems. sequence('\r\n').

The following is sample code that uses lineSeparator()the method to get the system line separator:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        String lineSeparator = System.lineSeparator();
        System.out.println("系统行分隔符是:" + lineSeparator);
    }
}

In the above code, we use lineSeparator()the method to get the system line separator and output it to the console. The output may vary depending on the operating system and Java version used.

Note: Use system line separators to ensure correct line wrapping on different operating systems. When outputting text, insert it where a line break is required to ensure that the line break effect can be displayed correctly in various environments.

11. exit(int status)

exit()It is a static method of Java's System class, used to terminate the currently running Java virtual machine. This method accepts an integer type parameter, usually used to represent the exit status of the program.

exit()The following is sample code to terminate a Java virtual machine using the method:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("程序正在运行...");

        // 调用 exit() 方法终止虚拟机
        System.exit(0);
    }
}

In the above code, when the program execution reaches System.exit(0), the Java virtual machine will terminate. Among them, the parameter 0indicates that the program exits normally. If you need to indicate an abnormal exit, you can use a non-zero value as a parameter.

Note: exit()Methods can only be called in the main thread of the application. In addition, before calling exit()the method, you should ensure that all created threads and objects have been properly released and closed to avoid resource leaks and other problems.

These methods make the System class a very useful tool in Java programs.

Three, Runtime

(1) Runtime overview

Java's Runtime class is part of Java's core class library. It provides an interface for Java to enable Java applications to interact with the underlying operating system. The Runtime class provides methods that enable Java applications to call operating system level functions.

The following are some of the main functions and methods of the Runtime class:

  1. Create a new process: The Runtime class provides the exec() method, which can be used to create a new process to execute external commands or programs. These methods accept a string or array of strings as parameters, representing the path and parameters of the command or program to be executed.
  2. Memory Management: The Runtime class provides some methods to manage the memory of Java applications. For example, the totalMemory() method returns the total amount of memory in the Java virtual machine, the freeMemory() method returns the amount of available memory, and the maxMemory() method returns the maximum amount of memory that the Java virtual machine can use.
  3. Interacting with the operating system: The Runtime class provides some methods to interact with the operating system. For example, the getenv() method can obtain the value of the specified environment variable, the getRuntime() method returns the Runtime object of the current Java virtual machine, the runFinalization() method runs all pending finalizers, and so on.
  4. Garbage collection: The Runtime class provides the gc() method to request the Java virtual machine to perform garbage collection. This can be used to manually manage memory for Java applications.

Note: Since the Runtime class is the core class that interacts with the underlying operating system, care needs to be taken when using the Runtime class to avoid security issues and resource leaks.

(2) Common methods of Runtime

The Runtime class provides many methods, some of the commonly used methods are as follows:

1. public static Runtime getRuntime()

public static Runtime getRuntime()Is a static method of Java's Runtime class that returns the Runtime object related to the current Java application. This method is an implementation of the singleton pattern, ensuring that only one Runtime instance is created, and the instance can be obtained by calling this method.

The following is a getRuntime()simple example of how to use a Runtime object to execute system commands:

import java.io.*;

public class RuntimeExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("notepad.exe"); // 执行系统命令
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
    
    
                System.out.println(line);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

The above example uses getRuntime()the method to obtain the Runtime object and calls exec()the method to execute the system command "notepad.exe". Then, by getting the input stream of the process, the output after the command execution can be read.

Precautions:

  1. The Runtime class is the core class that interacts with the underlying operating system, so care needs to be taken when using the Runtime class to avoid security issues and resource leaks.
  2. When using exec()methods to execute external commands, you should always handle exceptions that may be thrown to avoid errors in your program.
  3. When the Java virtual machine is shut down, all processes created through the Runtime class may not be shut down automatically. In order to avoid resource leaks, the relevant processes should be manually closed after using the Runtime object.

2. public Process exec(String command)

public Process exec(String command)It is a method of Java's Runtime class, used to execute the specified string command in a separate process, and returns a Process object representing the process.

Method parameters:

  • command: A string representing the command string to be executed.

return value:

  • A Process object representing the execution results of the new process.

Use this method to execute specified commands in a separate process. Through the returned Process object, you can obtain the output of the process, wait for the completion of process execution, process the input of the process, etc. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ls");

The above example uses the Runtime object to call the exec() method to execute the "ls" command and returns a Process object representing the process. This object allows further processing of the process's output.

3. public Process exec(String[] cmdarray)

public Process exec(String[] cmdarray)Is a method of Java's Runtime class that is used to execute the commands in the string array in a separate process and returns a Process object representing the process.

Method parameters:

  • cmdarray: An array of strings representing the command to be executed and its parameters.

return value:

  • A Process object representing the execution results of the new process.

Use this method to execute a command and its arguments in a separate process. Through the returned Process object, you can obtain the output of the process, wait for the completion of process execution, process the input of the process, etc. Here's a simple example:

String[] cmdarray = {
    
    "ls", "-l"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmdarray);

The above example uses the Runtime object to call the exec() method to execute the "ls -l" command and returns a Process object representing the process. This object allows further processing of the process's output.

4. public Process exec(String[] cmdarray, String[] envp)

public Process exec(String[] cmdarray, String[] envp)It is a method of Java's Runtime class, used to execute the commands in the string array in a separate process, and uses the specified environment variable array to set the environment variables of the child process, and returns a Process object representing the process.

Method parameters:

  • cmdarray: An array of strings representing the command to be executed and its parameters.
  • envp: An array of strings representing the environment variables to be passed to the child process.

return value:

  • A Process object representing the execution results of the new process.

Use this method to execute a command in a separate process and use the specified environment variables to set the environment variables of the child process. Through the returned Process object, you can obtain the output of the process, wait for the completion of process execution, process the input of the process, etc. Here's a simple example:

String[] cmdarray = {
    
    "ls", "-l"};
String[] envp = {
    
    "PATH=/usr/local/bin"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmdarray, envp);

The above example uses the Runtime object to call the exec() method to execute the "ls -l" command, and uses the specified array of environment variables to set the environment variables of the child process. The output of the process can be further processed through the returned Process object.

5. public Process exec(String command, String[] envp)

public Process exec(String command, String[] envp)It is a method of Java's Runtime class, used to execute the specified string command in a separate process, use the specified environment variable array to set the environment variables of the child process, and return a Process object representing the process.

Method parameters:

  • command: A string representing the command string to be executed.
  • envp: An array of strings representing the environment variables to be passed to the child process.

return value:

  • A Process object representing the execution results of the new process.

Use this method to execute the specified command in a separate process and use the specified environment variable to set the environment variable of the child process. Through the returned Process object, you can obtain the output of the process, wait for the completion of process execution, process the input of the process, etc. Here's a simple example:

String command = "ls";
String[] envp = {
    
    "PATH=/usr/local/bin"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command, envp);

The above example uses the Runtime object to call the exec() method to execute the "ls" command and uses the specified array of environment variables to set the environment variables of the child process. The output of the process can be further processed through the returned Process object.

6. public long freeMemory()

public long freeMemory()Is a method of Java's Runtime class used to return the amount of free memory in the Java virtual machine.

return value:

  • A long value representing the amount of free memory in the Java virtual machine.

Use this method to obtain the amount of free memory of the Java virtual machine for performance optimization and memory management. It should be noted that the amount of free memory returned by this method is based on the JVM's internal statistics, not the amount of free physical memory. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
long freeMemory = runtime.freeMemory();
System.out.println("Free memory: " + freeMemory + " bytes");

The above example uses the Runtime object to call the freeMemory() method to obtain the amount of free memory of the Java virtual machine and output it to the console.

7. public long maxMemory()

public long maxMemory()Is a method of Java's Runtime class that returns the maximum amount of memory that the Java virtual machine attempts to use.

return value:

  • A long value that represents the maximum amount of memory that the Java virtual machine attempts to use.

Use this method to obtain the maximum amount of memory that the Java virtual machine attempts to use for performance optimization and memory management. It should be noted that the value returned by this method is automatically set by the JVM according to the operating system and system configuration when starting, and is not necessarily the maximum available amount of physical memory. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
System.out.println("Max memory: " + maxMemory + " bytes");

The above example uses the Runtime object to call the maxMemory() method to obtain the maximum amount of memory that the Java virtual machine attempts to use, and outputs it to the console.

8. public long totalMemory()

public long totalMemory()It is a method of Java's Runtime class, used to return the total amount of memory in the Java virtual machine.

return value:

  • A long integer value representing the total amount of memory in the Java virtual machine.

Use this method to obtain the total memory of the Java virtual machine for performance optimization and memory management. It should be noted that the total amount of memory returned by this method is automatically set by the JVM based on the operating system and system configuration when starting, and is not necessarily the total capacity of physical memory. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
long totalMemory = runtime.totalMemory();
System.out.println("Total memory: " + totalMemory + " bytes");

The above example uses the Runtime object to call the totalMemory() method to obtain the total memory in the Java virtual machine and output it to the console.

9. public void gc()

public void gc()It is a method of Java's Runtime class, used to request the Java virtual machine to perform garbage collection.

Use this method to request the JVM to recycle objects that are no longer used and release memory space to avoid problems such as memory leaks and memory overflows. It should be noted that this method only makes a request, and the JVM may choose to ignore the request because the JVM has the right to manage memory and garbage collection on its own. Therefore, there is no guarantee that memory will be released after calling this method. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
runtime.gc();

The above example uses the Runtime object to call the gc() method to request the JVM to perform garbage collection.

10. public void runFinalization()

public void runFinalization()Is a method of Java's Runtime class, used to run all pending finalizers.

Use this method to call the object's finalization method, release the resources occupied by the object, and reclaim memory space. It should be noted that this method only runs all pending finalizers, rather than forcing all finalizers to be executed. If the object does not define a finalizer or has already executed a finalizer, calling this method will have no effect. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
runtime.runFinalization();

The above example uses a Runtime object to call the runFinalization() method to run all pending finalizers.

11. public void addShutdownHook(Thread hook)

public void addShutdownHook(Thread hook)It is a method of Java's Runtime class, used to add a shutdown hook.

Method parameters:

  • hook: A thread object representing the shutdown hook to be added.

Use this method to perform some operations when the JVM is shut down, such as closing the database connection, saving data, etc. When the JVM receives a shutdown signal (such as the user pressing Ctrl + C), all added shutdown hooks will be executed in the order in which they were added. Here's a simple example:

Runtime runtime = Runtime.getRuntime();
Thread hook = new Thread(() -> {
    
    
    System.out.println("Shutting down...");
    // 关闭数据库连接、保存数据等操作
});
runtime.addShutdownHook(hook);

The above example uses the Runtime object to call the addShutdownHook() method to add a shutdown hook that outputs a message when the JVM shuts down and performs some shutdown operations.

These methods can help Java applications execute external commands, manage memory, handle garbage collection, etc. Please note that methods using the Runtime class need to be handled with caution to avoid security issues and resource leaks.

Four, Object

(1) Object Overview

In Java, Object class is the base class of all classes, which means that every class inherits from Object class directly or indirectly. The Object class is at the bottom of the Java language and contains the basic properties and methods of all Java objects.

(2) Construction method of Object

In Java, the Object class is the base class of all classes, which defines some basic properties and methods. There is a default no-argument constructor in the Object class, which is used to create object instances.

A default constructor is defined in the Object class, which has no parameters and is used to create new object instances. When a class does not provide a constructor, the system automatically calls the default constructor of the Object class to create the object.

The following is the code of the Object class constructor:

public Object() {
    
    
    // 默认构造函数
}

When creating a custom class, if no constructor is provided, the system defaults to calling the parameterless constructor of the Object class to create the object. If you need to provide a custom constructor, you need to override the default constructor of the Object class in the class.

It should be noted that if a class does not explicitly provide a constructor, the system calls the default constructor of the Object class by default. If a class provides its own constructor, the system will not automatically call the constructor of the parent class. In this case, you need to super()explicitly call the constructor of the parent class using the keyword.

(3) Member methods of Object

In addition to the constructor method, the Object class also defines some other commonly used member methods, as follows:

  1. equals(Object obj): Compares two objects for equality. By default, it uses "reference equality", that is, two references are equal if they point to the same object. However, many classes override this method to implement "object equality", that is, two objects are equal if their contents are equal.
  2. hashCode(): Returns the hash code value of the object. In Java, hash codes are commonly used to store objects in hash tables such as HashMap and HashSet.
  3. getClass(): Returns the runtime class of the object.
  4. clone(): Creates and returns a copy of this object. It should be noted that this method will only be used when the object implements the Cloneable interface, otherwise a CloneNotSupportedException exception will be thrown.
  5. toString(): Returns the string representation of the object. For the String class, this method returns the string itself. For other classes, this method usually returns the name of the class and the hexadecimal representation of its hash code.
  6. wait(), notify(), notifyAll(): These methods are used to handle thread locking and communication of objects, and they are all part of Java's built-in synchronization mechanism.

In addition to the above member methods, the Object class also defines some other methods and fields, such as hashCodefields (used to store hash codes of objects), etc. It should be noted that although the Object class provides many useful methods, not all Java classes need to use these methods. For custom classes, you can choose which methods of the Object class to use according to your needs.

五,Objects

(1) Overview of Objects

In Java, the Objects class is part of the Java standard library and is located in the java.util package. The Objects class provides some static methods for manipulating and processing objects. These methods cover object comparison, null value processing, object conversion, etc.

(2) Common methods of Objects

In Java, the Objects class is a tool class that provides some commonly used object operation methods. The following are some common methods of the Objects class:

1. equals(Object obj)

equals(Object obj)It is a method of Java's Object class, which is used to compare whether two objects are equal. This method first checks whether the passed object obj and the object calling the equals method are the same object, that is, the comparison is reference equality. If they are the same object, then return true, otherwise continue to compare the values ​​of the objects for equality.

In Java, the default equals method uses "reference equality" comparison, that is, if the references of two objects are the same reference, then they are equal. However, for custom classes, we usually need to implement our own equals method to compare whether the values ​​of objects are equal.

When overriding the equals method, you need to follow the following rules:

  1. The equals method must be public.
  2. The parameters of the equals method must be of type Object.
  3. The equals method must return a Boolean value indicating whether the two objects are equal.
  4. The equals method must produce a non-null result for any non-null argument.

When implementing the equals method, you need to compare whether the attribute values ​​of two objects are equal. For example, for a Person class, we may need to compare whether the name, age and other attributes of two Person objects are equal. If all properties are equal, then the two Person objects are equal.

It should be noted that the implementation of the equals method should be consistent with the implementation of the hashCode method to ensure that objects can be processed correctly when using hash tables (such as HashMap and HashSet).

The following are equals(Object obj)examples of methods:

public class Person {
    
    
    private String name;
    private int age;

    // 构造方法、getter和setter方法省略

    @Override
    public boolean equals(Object obj) {
    
    
        if (obj == this) {
    
    
            return true;
        }
        if (!(obj instanceof Person)) {
    
    
            return false;
        }
        Person other = (Person) obj;
        return this.name.equals(other.name) && this.age == other.age;
    }
}

In the above example, we overridden the equals method of the Person class to compare whether the names and ages of the two Person objects are equal. It should be noted that when comparing objects, you need to first determine whether the passed object is a reference to the current object. If so, return true; then determine whether the passed object is an instance of the class to which the current object belongs. If not, return false. ;Finally compare whether the attribute values ​​of the two objects are equal.

2. hashCode()

hashCode()It is a method of Java's Object class, which is used to return the hash code value of the object. A hash code is an integer that is calculated based on the actual contents of the object and can be used to quickly find the object.

In Java, every object has a default hashCode method that can calculate a hash code value based on the actual content of the object. This hash code value can be used to store the object in a hash table so that the object can be quickly found and accessed.

It should be noted that if the equals method of two objects returns true, then their hashCode method must return the same value. Therefore, when overriding the equals method, you usually also need to override the hashCode method to ensure their consistency.

The following are hashCode()examples of methods:

public class Person {
    
    
    private String name;
    private int age;

    // 构造方法、getter和setter方法省略

    @Override
    public int hashCode() {
    
    
        int result = 17;
        result = 31 * result + name.hashCode();
        result = 31 * result + age;
        return result;
    }
}

In the above example, we overridden the hashCode method of the Person class to calculate a hash code value based on the actual content of the object. It should be noted that multiplication and a prime number (31) are used to calculate the hash code. This is to ensure an even distribution of hash codes and reduce conflicts.

3. toString()

toString()It is a method of Java's Object class, which is used to return the string representation of the object. By default, the toString method of the Object class returns a meaningless string representation of the object's class name and hash code.

For custom classes, we usually need to implement our own toString method in order to return a meaningful string representation of the object. The implementation of the toString method should accurately reflect the internal state of the object, including all important property values.

When overriding the toString method, you need to follow the following rules:

  1. The toString method must be public.
  2. The return type of the toString method must be String.
  3. When implementing the toString method, you can use the StringBuilder or StringBuffer classes to build the string.

The following are toString()examples of methods:

public class Person {
    
    
    private String name;
    private int age;

    // 构造方法、getter和setter方法省略

    @Override
    public String toString() {
    
    
        StringBuilder sb = new StringBuilder();
        sb.append("Person{name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }
}

In the above example, we overridden the toString method of the Person class to return the string representation of the object. The StringBuilder class is used here to build a string, and the string representation of the object's name attribute and age attribute is added.

4. requireNonNull(T value, String message)

requireNonNull(T value, String message)It is a static method in Java's Objects class. It is used to check if the passed parameter value is null and if so, throws a NullPointerException with a custom error message.

The signature of this method is as follows:

public static <T> T requireNonNull(T value, String message)

Parameter Description:

  • T value: The generic parameter value to check.
  • String message: Customized error message used to provide detailed error information when NullPointerException is thrown.

Return value: Returns the passed parameter value.

Usage example:

String str = Objects.requireNonNull(getNullableString(), "The string is null");

In the above example, we are calling requireNonNulla method to check getNullableString()if the string returned from the method is null. If null, throws a NullPointerException with a custom error message "The string is null".

This method is particularly useful because it allows us to catch errors early when important parameters passed to a method or constructor are null, thus improving the readability and robustness of the code.

5. nullToEmpty(String string)

nullToEmpty(String string)It is a static method in Java's Objects class. Its function is to convert the incoming string parameter into an empty string, and if the string is null, return an empty string "".

The signature of this method is as follows:

public static String nullToEmpty(String string)

Parameter Description:

  • String string: The string parameter to be converted.

Return value: Returns the converted string. If the incoming string is null, the empty string "" is returned.

Usage example:

String str = null;
String emptyStr = Objects.nullToEmpty(str); // emptyStr的值为""

In the above example, we passed a null value to nullToEmptythe method and it returned an empty string "". This method avoids NullPointerException when handling strings because it converts null values ​​to empty strings, making the code more robust and easier to handle.

6. copy(T original, T dest)

copy(T original, T dest)It is a static method in Java's Objects class. Its function is to copy the contents of the original object to the target object.

The signature of this method is as follows:

public static <T> void copy(T original, T dest)

Parameter Description:

  • T original: The original object whose contents will be copied to the target object.
  • T dest: Target object whose contents will be overwritten by the original object.

Return value: No return value.

Usage example:

List<Integer> original = Arrays.asList(1, 2, 3);
List<Integer> dest = new ArrayList<>();
Objects.copy(original, dest); // dest的内容被复制为[1, 2, 3]

In the above example, we use copythe method to copy the contents of the original list originalto the target list dest. Note that the target object must be a compatible instance of the original object in order to successfully copy the original object's contents.

7. deepEquals(Object a, Object b)

deepEquals(Object a, Object b)It is a static method in Java's Objects class. It is used to deeply compare two objects for equality, including nested objects.

The signature of this method is as follows:

public static boolean deepEquals(Object a, Object b)

Parameter Description:

  • Object a: Object a to be compared.
  • Object b: Object b to be compared.

Return value: Returns a Boolean value indicating whether the depths of the two objects are equal. Returns true if they are equal, false otherwise.

Usage example:

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2, 3);
boolean isEqual = Objects.deepEquals(list1, list2); // isEqual的值为true

In the above example, we deepEqualscompared two list objects using the method list1sum list2. Since the contents of the two lists are exactly the same, deepEqualsthe method returns true, indicating that the two lists are of equal depth.

8. <T> T firstNonNull(T... values)

<T> T firstNonNull(T... values)Is a Java method that accepts a generic variable parameter T... valuesand returns the first value that is not null.

The implementation of this method is as follows:

public static <T> T firstNonNull(T... values) {
    
    
    for (T value : values) {
    
    
        if (value != null) {
    
    
            return value;
        }
    }
    throw new NullPointerException("All values are null");
}

This method iterates through the passed valuesarray and if a value is found to be non-null, it returns that value immediately. If no value that is not null is found after traversing the entire array, NullPointerExceptionan exception is thrown.

This method is useful when dealing with multiple possibly null values ​​and avoids checking for null values ​​repeatedly in your code.

9. format(String format, Object... args)

String.format(String format, Object... args)Is a static method in Java for formatting strings. This method accepts a format string and a variable number of arguments, and returns a new format string.

The format string contains plain text and conversion specifications. The conversion specifier indicates that the parameter should be inserted somewhere in the string. For example, %dit is a conversion specification that inserts an integer at that position in the string.

Here are some String.format()examples of using :

String name = "John";
int age = 25;
String greeting = String.format("Hello, %s. You are %d years old.", name, age);
System.out.println(greeting); // 输出:Hello, John. You are 25 years old.

In this example, %sit's a conversion specifier that inserts a string at that position in the string. %dIt is also a conversion specification character, which means inserting an integer at this position in the string.

In addition to %sand %d, Java also provides some other conversion specifications, such as %f(floating point number), %c(character), %b(Boolean value), etc. Consult the Java documentation for a complete list of conversion specifiers.

These methods are common methods of the Objects class in Java, which can facilitate object manipulation and management.

Guess you like

Origin blog.csdn.net/m0_62617719/article/details/132712207