Skip to content
On this page

Commonly used tools

Java's core library provides a large number of ready-made classes for us to use. In this section we introduce several commonly used tool classes.

Math

As the name suggests, the Math class is used for mathematical calculations. It provides a large number of static methods to facilitate us to implement mathematical calculations:

Find the absolute value:

java
Math.abs(-100); // 100
Math.abs(-7.8); // 7.8

Take the maximum or minimum value:

java
Math.max(100, 99); // 100
Math.min(1.2, 2.3); // 1.2

Calculate x raised to the y power:

java
Math.pow(2, 10); // 2 to the 10th power=1024

calculate x

java
Math.sqrt(2); // 1.414...

Calculate ex to the power:

java
Math.exp(2); // 7.389...

Compute the logarithm to the base e:

java
Math.log(4); // 1.386...

Compute the base 10 logarithm:

java
Math.log10(100); // 2

Trigonometric functions:

java
Math.sin(3.14); // 0.00159...
Math.cos(3.14); // -0.9999...
Math.tan(3.14); // -0.0015...
Math.asin(1.0); // 1.57079...
Math.acos(1.0); // 0.0

Math also provides several mathematical constants:

java
double pi = Math.PI; // 3.14159...
double e = Math.E; // 2.7182818...
Math.sin(Math.PI / 6); // sin(π/6) = 0.5

Generate a random number x, the range of x is 0 <= x < 1 :

java
Math.random(); // 0.53907... 每次都不一样

If we want to generate a random number in the range [MIN, MAX) , we can use Math.random() to achieve it. The calculation is as follows:

java
// Random number in the range [MIN, MAX)
public class Main {
    public static void main(String[] args) {
        double x = Math.random(); // The range of x is [0,1)
        double min = 10;
        double max = 50;
        double y = x * (max - min) + min; // The range of y is [10,50)
        long n = (long) y; // The range of n is an integer of [10,50)
        System.out.println(y);
        System.out.println(n);
    }
}

Some students may have noticed that the Java standard library also provides a StrictMath , which provides almost the same method as Math .

The difference between these two classes is that due to errors in floating-point calculations, the calculation results of different platforms (such as x86 and ARM) may be inconsistent (referring to different errors).

Therefore, StrictMath guarantees that the calculation results of all platforms are exactly the same, while Math will try its best to optimize the calculation speed for the platform, so in most cases, using Math is enough.

HexFormat

When processing byte[] arrays, we often need to convert hexadecimal strings. It is troublesome to write it ourselves. HexFormat provided by the Java standard library can easily help us convert.

To convert byte[] array to a hexadecimal string, you can use formatHex() method:

java
import java.util.HexFormat;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        byte[] data = "Hello".getBytes();
        HexFormat hf = HexFormat.of();
        String hexData = hf.formatHex(data); // 48656c6c6f
    }
}

If you want to customize the conversion format, use a customized HexFormat instance:

java
HexFormat hf = HexFormat.ofDelimiter(" ").withPrefix("0x").withUpperCase();
hf.formatHex("Hello".getBytes())); // 0x48 0x65 0x6C 0x6C 0x6F

To convert from a hexadecimal string to a byte[] array, use parseHex() method:

java
byte[] bs = HexFormat.of().parseHex("48656c6c6f");

Random

Random is used to create pseudo-random numbers. The so-called pseudo-random number means that as long as an initial seed is given, the random number sequence generated is exactly the same.

To generate a random number, you can use nextInt() , nextLong() , nextFloat() , nextDouble() :

java
Random r = new Random();
r.nextInt(); // 2071575453,different every time
r.nextInt(10); // 5,Generate an int between [0,10)
r.nextLong(); // 8811649292570369305,different every time
r.nextFloat(); // 0.54335...Generate a float between [0,1)
r.nextDouble(); // 0.3716...Generate a double between [0,1)

Some children asked that every time the program is run, the random numbers generated are different, and the characteristics of pseudo-random numbers are not seen.

This is because when we create a Random instance, if we do not give a seed, we use the current timestamp of the system as the seed. Therefore, every time it is run, the seed is different and the pseudo-random number sequence obtained is different.

If we specify a seed when creating a Random instance, we will get a completely deterministic random number sequence:

java
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random r = new Random(12345);
        for (int i = 0; i < 10; i++) {
            System.out.println(r.nextInt(100));
        }
        // 51, 80, 41, 28, 55...
    }
}

Math.random() we used earlier actually calls Random class internally, so it is also a pseudo-random number, but we cannot specify the seed.

SecureRandom

There are pseudo-random numbers and there are true random numbers. In fact, true random numbers can only be obtained through the principles of quantum mechanics, and what we want is an unpredictable and secure random number. SecureRandom is used to create secure random numbers:

java
SecureRandom sr = new SecureRandom();
System.out.println(sr.nextInt(100));

SecureRandom cannot specify a seed, it uses the RNG (random number generator) algorithm. JDK's SecureRandom actually has a variety of different underlying implementations. Some use a secure random seed plus a pseudo-random number algorithm to generate secure random numbers, and some use a true random number generator.

In actual use, you can give priority to obtaining a high-strength secure random number generator. If it is not provided, use an ordinary-level secure random number generator:

java
import java.util.Arrays;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] args) {
        SecureRandom sr = null;
        try {
            sr = SecureRandom.getInstanceStrong(); // Get a strong secure random number generator
        } catch (NoSuchAlgorithmException e) {
            sr = new SecureRandom(); // Get a plain secure random number generator
        }
        byte[] buffer = new byte[16];
        sr.nextBytes(buffer); // Fill buffer with secure random numbers
        System.out.println(Arrays.toString(buffer));
    }
}

The security of SecureRandom is to generate random numbers through a secure random seed provided by the operating system. This seed is "entropy" generated by various random events such as CPU thermal noise, bytes read and written to disk, network traffic, etc.

In cryptography, secure random numbers are very important. If insecure pseudo-random numbers are used, all encryption systems will be broken. Therefore, always remember SecureRandom must be used to generate secure random numbers.

Notice

When you need to use secure random numbers, you must use SecureRandom and never use Random!

Summary

Common tool classes provided by Java include:

  • Math: mathematical calculations
  • HexFormat: Format hexadecimal number
  • Random: generate pseudo-random numbers
  • SecureRandom: Generate secure random numbers
Commonly used tools has loaded