API s commonly used in java: Math class, Random class, Integer class, BigInteger class and BigDecimal class

Posted by khaine on Tue, 05 Oct 2021 23:17:03 +0200

        This chapter mainly summarizes the common API s related to numbers in java, including Math class, Random class, Integer class, BigInteger class and BigDecimal class, which mainly involves the operation and type of numbers.

1. Math class

        Math is a class used for mathematical operations. The common math class members are as follows:

  Member variables:

        public static final double PI

        public static final double E

  Member method:

        public static int abs(int a): absolute value

        public static double ceil(double a): round up

        public static double floor(double a): round down

        public static int max(int a,int b): maximum value (min)

        Public static double pow (double a, double b): power b of a

        public static double random(): random number [0.0,1.0]

        public static int round(float a) round (self-study with double parameter)

        public static double sqrt(double a): positive square root

public class TestDemo {
	public static void main(String[] args) {
		// public static final double PI
		System.out.println("PI:" + Math.PI);
		// public static final double E
		System.out.println("E:" + Math.E);
		System.out.println("--------------");

		// public static int abs(int a): absolute value
		System.out.println("abs:" + Math.abs(10));
		System.out.println("abs:" + Math.abs(-10));
		System.out.println("--------------");

		// public static double ceil(double a): round up
		System.out.println("ceil:" + Math.ceil(12.34));
		System.out.println("ceil:" + Math.ceil(12.56));
		System.out.println("--------------");

		// public static double floor(double a): round down
		System.out.println("floor:" + Math.floor(12.34));
		System.out.println("floor:" + Math.floor(12.56));
		System.out.println("--------------");

		// public static int max(int a,int b): maximum
		System.out.println("max:" + Math.max(12, 23));
		// Requirement: I want to get the maximum of the three data
		// Nested calls to methods
		System.out.println("max:" + Math.max(Math.max(12, 23), 18));
		// Requirement: I want to get the maximum of the four data
		System.out.println("max:"
				+ Math.max(Math.max(12, 78), Math.max(34, 56)));
		System.out.println("--------------");

		// Public static double pow (double a, double b): power b of a
		System.out.println("pow:" + Math.pow(2, 3));
		System.out.println("--------------");

		// public static double random(): random number [0.0,1.0]
		System.out.println("random:" + Math.random());
		// Get a random number between 1 and 100
		System.out.println("random:" + ((int) (Math.random() * 100) + 1));
		System.out.println("--------------");

		// public static int round(float a) round (self-study with double parameter)
		System.out.println("round:" + Math.round(12.34f));
		System.out.println("round:" + Math.round(12.56f));
		System.out.println("--------------");
		
		//public static double sqrt(double a): positive square root
		System.out.println("sqrt:"+Math.sqrt(4));
	}
}

  1.1. Math.Random() case

//Case: to obtain random numbers in any range

//public static double random(): random number [0.0,1.0]
public class MathDemo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter the starting number:");
		int start = sc.nextInt();
		System.out.println("Please enter the ending number:");
		int end = sc.nextInt();

		for (int x = 0; x < 100; x++) {
			// Call function
			int num = getRandom(start, end);
			// Output results
			System.out.println(num);
		}
	}

	/*
	 * Write a function with two explicit: return value type: int parameter list: int start,int end
	 */
	public static int getRandom(int start, int end) {
		// Recall that we talked about random numbers between 1 and 100
		// int number = (int) (Math.random() * 100) + 1;
		// int number = (int) (Math.random() * end) + start; 
		// 200300 found a problem. What should I do?
		int number = (int) (Math.random() * (end - start + 1)) + start;
		return number;
	}
}

2. Random class

        Random means arbitrary and random. In java, it is a class used to generate random numbers. The members of common random classes are as follows:

  Random() construction method:

        public Random(): no seed is given, but the default seed is used, which is the millisecond value of the current time

        public Random(long seed): gives the specified seed

  Given a seed, the random number obtained each time is the same.

  Member method:

        public int nextInt(): returns a random number within the range of int

        public int nextInt(int n): returns a random number within the range of [0,n)

public class TestDemo {
	public static void main(String[] args) {
		// create object
		// Random r = new Random();
		Random r = new Random(1111); //After Random(long seed) gives the specified seed, the result of each run is the same

		for (int x = 0; x < 10; x++) {
			// int num = r.nextInt();
			int num = r.nextInt(100) + 1;
			System.out.println(num);
		}
	}
}

3. Integer class

        The Integer class wraps the value of the original type int in an object. An object of type Integer contains a single field of type int. in addition, the class provides some constants and methods for converting int to String and String to int, as well as other constants and methods useful in dealing with int.

  3.1 construction method of Integer

/*
 * Integer Construction method:
 * public Integer(int value)
 * public Integer(String s)  Note: this string must be composed of numeric characters
 * 		
 */
public class IntegerDemo {
	public static void main(String[] args) {
		// Mode 1
		int i = 100;
		Integer ii = new Integer(i);
		System.out.println("ii:" + ii);

		// Mode 2
		String s = "100";
		// NumberFormatException
		// String s = "abc";
		Integer iii = new Integer(s);
		System.out.println("iii:" + iii);
	}
}

3.2 conversion between Integer and String types

  Convert int to String

       String.valueOf(number)

  Convert String to int

       Integer.parseInt(s)

public class TestDemo {
	public static void main(String[] args) {
		// int -- String
		int number = 100;
		// Mode 1
		String s1 = "" + number;
		System.out.println("s1:" + s1);
		// Mode 2
		String s2 = String.valueOf(number);
		System.out.println("s2:" + s2);
		// Mode 3
		// int -- Integer -- String
		Integer i = new Integer(number);
		String s3 = i.toString();
		System.out.println("s3:" + s3);
		// Mode 4
		// public static String toString(int i)
		String s4 = Integer.toString(number);
		System.out.println("s4:" + s4);
		System.out.println("-----------------");

		// String -- int
		String s = "100";
		// Mode 1
		// String -- Integer -- int
		Integer ii = new Integer(s);
		// public int intValue()
		int x = ii.intValue();
		System.out.println("x:" + x);
		//Mode 2
		//public static int parseInt(String s)
		int y = Integer.parseInt(s);
		System.out.println("y:"+y);
	}
}

3.3 conversion of Integer base

int type is converted to binary, octal and hexadecimal, and the string representation is returned

        public static String toBinaryString(int i) returns the binary of the string

         public static String toOctalString(int i) returns the octal of the string

        public static String toHexString(int i) returns the hexadecimal of the string

  int type can flexibly convert other base numbers and return string representation

          Public static string toString (int i, int radius) converts the I value of int type into a radix number and returns the string form

Other hexadecimals can be flexibly converted to int type

        Public static int parseInt (string s, int radius) returns the equivalent number of int type words by the number of the string corresponding to the radix number.

public class TestDemo {
	public static void main(String[] args) {
		// Decimal to binary, octal, hexadecimal
		System.out.println(Integer.toBinaryString(100));
		System.out.println(Integer.toOctalString(100));
		System.out.println(Integer.toHexString(100));
		System.out.println("-------------------------");

		// Decimal to other base
		System.out.println(Integer.toString(100, 10));
		System.out.println(Integer.toString(100, 2));
		System.out.println(Integer.toString(100, 8));
		System.out.println(Integer.toString(100, 16));
		System.out.println(Integer.toString(100, 5));
		System.out.println(Integer.toString(100, 7));
		System.out.println(Integer.toString(100, -7));
		System.out.println(Integer.toString(100, 70));
		System.out.println(Integer.toString(100, 1));
		System.out.println(Integer.toString(100, 17));
		System.out.println(Integer.toString(100, 32));
		System.out.println(Integer.toString(100, 37));
		System.out.println(Integer.toString(100, 36));
		System.out.println("-------------------------");
		
		//Other base to decimal
		System.out.println(Integer.parseInt("100", 10));
		System.out.println(Integer.parseInt("100", 2));
		System.out.println(Integer.parseInt("100", 8));
		System.out.println(Integer.parseInt("100", 16));
		System.out.println(Integer.parseInt("100", 23));
		//NumberFormatException
		//System.out.println(Integer.parseInt("123", 2));
	}
}

3.4. The data of Integer is directly assigned in the range of - 128 to 127

Direct assignment is in the form of Integer i7 = 127,

Note: the data of Integer is directly assigned. If it is between - 128 and 127, the data will be directly obtained from the buffer pool

public class IntegerDemo {
	public static void main(String[] args) {
		Integer i1 = new Integer(127);
		Integer i2 = new Integer(127);
		System.out.println(i1 == i2);
		System.out.println(i1.equals(i2));
		System.out.println("-----------");

		Integer i3 = new Integer(128);
		Integer i4 = new Integer(128);
		System.out.println(i3 == i4);
		System.out.println(i3.equals(i4));
		System.out.println("-----------");

		Integer i5 = 128;
		Integer i6 = 128;
		System.out.println(i5 == i6);
		System.out.println(i5.equals(i6));
		System.out.println("-----------");

		Integer i7 = 127;
		Integer i8 = 127;
		System.out.println(i7 == i8);
		System.out.println(i7.equals(i8));

		// By looking at the source code, we know that a data buffer pool is made for the data between - 128 and 127. If the data is within this range, no new space is created each time
		// Integer ii = Integer.valueOf(127);
	}
}
/* The results are as follows
false    //This is because the new object refers to the address of the heap object first, and then the address of the character constant pool
true
-----------
false
true
-----------
false
true
-----------
true
true
*/

4. BigInteger class

        BigInteger allows data beyond the range of Integer to operate.

  4.1 construction method of BigInteger class

         BigInteger(String val)

import java.math.BigInteger; //To import packages

public class TestDemo {
	public static void main(String[] args) {
		// The purpose of these tests is to simply exceed the int range, and Integer can no longer be expressed, so let alone calculation.
		// Integer i = new Integer(100);
		// System.out.println(i);
		// // System.out.println(Integer.MAX_VALUE);
		// Integer ii = new Integer("2147483647");
		// System.out.println(ii);
		// // NumberFormatException
		// Integer iii = new Integer("2147483648");
		// System.out.println(iii);

		// Create objects with large integers
		BigInteger bi = new BigInteger("2147483648");
		System.out.println("bi:" + bi);
	}
}

   4.2 addition, subtraction, multiplication and division of BigInteger

  public BigInteger add(BigInteger val): add

  public BigInteger subtract(BigInteger val): subtract

  public BigInteger multiply(BigInteger val): multiply

  public BigInteger divide(BigInteger val): divide

  Public BigInteger [] divideandremander (BigInteger VAL): returns an array of quotient and remainder

import java.math.BigInteger;

public class TestDemo {
	public static void main(String[] args) {
		BigInteger bi1 = new BigInteger("100");
		BigInteger bi2 = new BigInteger("50");

		// public BigInteger add(BigInteger val): add
		System.out.println("add:" + bi1.add(bi2));
		// Public BigInteger subcontract (BigInteger VAL): add
		System.out.println("subtract:" + bi1.subtract(bi2));
		// public BigInteger multiply(BigInteger val): add
		System.out.println("multiply:" + bi1.multiply(bi2));
		// public BigInteger divide(BigInteger val): add
		System.out.println("divide:" + bi1.divide(bi2));

		// Public BigInteger [] divideandremander (BigInteger VAL): returns an array of quotient and remainder
		BigInteger[] bis = bi1.divideAndRemainder(bi2);
		System.out.println("Business:" + bis[0]);
		System.out.println("remainder:" + bis[1]);
	}
}

5. BigDecimal class

        In order to accurately represent and calculate float ing-point numbers, Java provides BigDecimal. BigDecimal class is an immutable signed decimal number with arbitrary precision, which can solve the problem of data loss.

  5.1 construction method and addition, subtraction, multiplication and division of BigDecimal class

  public BigDecimal(String val) construction method

 public BigDecimal add(BigDecimal augend)

 public BigDecimal subtract(BigDecimal subtrahend)

 public BigDecimal multiply(BigDecimal multiplicand)

 public BigDecimal divide(BigDecimal divisor)

  Public BigDecimal divide (BigDecimal division, int scale, int roundingmode): quotient, several decimal places, how to round off

import java.math.BigDecimal;

public class TestDemo {
	public static void main(String[] args) {
		// System.out.println(0.09 + 0.01);
		// System.out.println(1.0 - 0.32);
		// System.out.println(1.015 * 100);
		// System.out.println(1.301 / 100);

		BigDecimal bd1 = new BigDecimal("0.09");
		BigDecimal bd2 = new BigDecimal("0.01");
		System.out.println("add:" + bd1.add(bd2));
		System.out.println("-------------------");

		BigDecimal bd3 = new BigDecimal("1.0");
		BigDecimal bd4 = new BigDecimal("0.32");
		System.out.println("subtract:" + bd3.subtract(bd4));
		System.out.println("-------------------");

		BigDecimal bd5 = new BigDecimal("1.015");
		BigDecimal bd6 = new BigDecimal("100");
		System.out.println("multiply:" + bd5.multiply(bd6));
		System.out.println("-------------------");

		BigDecimal bd7 = new BigDecimal("1.301");
		BigDecimal bd8 = new BigDecimal("100");
		System.out.println("divide:" + bd7.divide(bd8));
		System.out.println("divide:"
				+ bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));
		System.out.println("divide:"
				+ bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));
	}
}

Topics: Java api