Java - common API (Math, System, Object, Arrays, basic type wrapper classes) 01

Math

Math class overview
Math contains methods to perform basic numerical operations

How to use members of a class without a constructor?
Check whether the members of the class are static. If so, they can be called directly through the class name

method name illustrate
public static int abs(int a) Returns the absolute value of the argument
public static double ceil(double a) Returns the smallest double value greater than or equal to the argument, equal to an integer
public static double floor(double a) Returns the largest double value less than or equal to the argument, equal to an integer
public static int round(float a) Returns the int closest to the argument according to rounding
public static int max(int a,int b) Returns the greater of two int values
public static int min(int a,int b) Returns the smaller of two int values
public static double pow(double a,double b) Returns the value of a raised to the power of b
public static double random() The return value is a positive value of double, [0.0,1.0)
public class MathDemo {
    
    
	public static void main(String[] args) {
    
    
//		public static int abs(int a)    返回参数的绝对值
		System.out.println(Math.abs(88));
		System.out.println(Math.abs(-88));
		System.out.println("——————————");

//		public static double ceil(double a)返回大于或等于参数的最小double值,等于一个整数
		System.out.println(Math.ceil(34.56));
		System.out.println(Math.ceil(54.74));
		System.out.println("——————————");

//		public static double floor(double a)返回小于或等于参数的最大double值,等于一个整数
		System.out.println(Math.floor(43.64));
		System.out.println(Math.floor(32.32));
		System.out.println("——————————");

//		public static int round(float a)按照四舍五入返回最接近参数的int
		System.out.println(Math.round(34.4F));
		System.out.println(Math.round(23.6F));
		System.out.println("——————————");

//		public static int max(int a,int b)返回两个int值中的较大值
		System.out.println(Math.max(4, 6));
		System.out.println(Math.max(43, 23));
		System.out.println("——————————");

//		public static int min(int a,int b)返回两个int值中的较小值
		System.out.println(Math.min(4, 6));
		System.out.println(Math.min(43, 23));
		System.out.println("——————————");

//		public static double pow(double a,double b)返回a的b次幂的值
		System.out.println(Math.pow(2.0, 2.0));
		System.out.println(Math.pow(4.5, 3.3));
		System.out.println("——————————");

//		public static double random()返回值为double的正值,[0.0,1.0)
		System.out.println(Math.random());
		System.out.println(Math.random() * 100);// 扩到100倍
		System.out.println((int) (Math.random() * 100));// 取整
		System.out.println("——————————");

	}

operation result:
insert image description here
insert image description here

System

System class overview
System contains several useful class fields and methods, it cannot be instantiated

Common methods of the System class

method name illustrate
public static void exit(int status) Terminates the currently running Java virtual machine, non-zero means abnormal termination
public static long current TimeMillis() Returns the current time in milliseconds
public class SystemDemo {
    
    
	public static void main(String[] args) {
    
    
//		System.out.println("开始");

//		 public static void exit(int status)   终止当前运行的Java虚拟机,非零表示异常终止
//		System.exit(0);
//		System.out.println("结束");//已经终止了Java虚拟机,不会再运行这一条

//		public static long current TimeMillis()返回当前时间(以毫秒为单位)
//		System.out.println(System.currentTimeMillis());//当前时间和1970年之间的毫秒值
		System.out.println(System.currentTimeMillis() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");// 当前时间和1970年之间的年数

		// 得知这个for循环用了多长时间
		long start = System.currentTimeMillis();
		for (int i = 0; i < 10000; i++) {
    
    
			System.out.println(i);
		}
		long end = System.currentTimeMillis();
		System.out.println("共耗时:" + (end - start) + "毫秒");

	}
}

Object

Overview of the Object class
Object is the root of the class hierarchy, and each class can have Object as a superclass. All classes inherit directly or indirectly from this class

Construction method: public Object()

Recalling object-oriented, why does the constructor of the subclass access the no-argument constructor of the parent class by default?
Because their top-level parent class only has no-argument constructors


//学生类
public class Student {
    
    
	private String name;
	private int age;

	public Student(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}

	public Student() {
    
    
		super();
	}

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}

	@Override
	public String toString() {
    
    
		return "Student [name=" + name + ", age=" + age + "]";
	}

}
//重写tostring方法
//测试类
public class ObjectDemo {
    
    
	public static void main(String[] args) {
    
    
		Student s = new Student();
		s.setName("小白");
		s.setAge(12);
		System.out.println(s);// API.Student@3ac3fd8b,原因如下
		System.out.println(s.toString());// 同上
		// 查看println源码
		/*
		 * public void println(Object x) { String s = String.valueOf(x); if (getClass()
		 * == PrintStream.class) { // need to apply String.valueOf again since first
		 * invocation // might return null writeln(String.valueOf(s)); } else {
		 * synchronized (this) { print(s); newLine(); } } }
		 * 
		 * public static String valueOf(Object obj) { return (obj == null) ? "null" :
		 * obj.toString(); }
		 * 
		 * public String toString() { return getClass().getName() + "@" +
		 * Integer.toHexString(hashCode()); }
		 */

	}
}

Running results:
insert image description here
common methods of the Object class

method name illustrate
public String toString() Returns a string representation of the object. It is recommended that all subclasses override this method and automatically generate
public boolean equals(Object obj) Compare objects for equality. The address is compared by default, and the content can be compared by rewriting, which is automatically generated
import java.util.Objects;

//学生类
public class Student {
    
    
	private String name;
	private int age;

	public Student(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}

	public Student() {
    
    
		super();
	}

	public String getName() {
    
    
		return name;
	}

	public void setName(String name) {
    
    
		this.name = name;
	}

	public int getAge() {
    
    
		return age;
	}

	public void setAge(int age) {
    
    
		this.age = age;
	}

	@Override
	public int hashCode() {
    
    
		return Objects.hash(age, name);
	}

//重写equals,自动生成
	@Override
	public boolean equals(Object obj) {
    
    
		// this---s1
		// obj---s2
		if (this == obj)// 比较地址值
			return true;
		if (obj == null)// 判断参数为null
			return false;
		if (getClass() != obj.getClass())// 判断是否来自同一个类
			return false;
		Student other = (Student) obj;// 向下转型,other----s2
		// age相同,然后调方法
		return age == other.age && Objects.equals(name, other.name);
	}
//重写tostring方法
//测试类
//public boolean equals(Object obj);指示一些其他对象是否等于此
public class ObjectDemo {
    
    
	public static void main(String[] args) {
    
    
		Student s1 = new Student();
		s1.setName("小白");
		s1.setAge(14);

		Student s2 = new Student();
		s2.setName("小白");
		s2.setAge(14);

		// 需求:比较两个对象的内容是否相同
//		System.out.println(s1==s2);//false,比较的是地址值
		System.out.println(s1.equals(s2));
		/*
		 * public boolean equals(Object obj) { this----s1 obj----s2 return (this ==
		 * obj); }
		 */

	}
}

operation result:
insert image description here

Arrays

Bubble sort
sorting: Sort a set of data according to fixed rules

Bubble sorting: A sorting method that compares adjacent data in the data to be sorted, puts the larger data behind, and operates on all the data in turn until all the data is sorted as required

  • If there are n data to be sorted, a total of n-1 comparisons are required
  • After each comparison, there will be one less data involved in the next comparison

//冒泡排序
public class ArrayDemo {
    
    
	public static void main(String[] args) {
    
    
		// 定义数组
		int[] arr = {
    
     12, 43, 54, 23, 56 };
		System.out.println("排序前:" + arrayToString(arr));

		for (int i = 0; i < arr.length - 1; i++) {
    
    
			for (int j = i + 1; j < arr.length; j++) {
    
    
				if (arr[i] > arr[j]) {
    
    
					int temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
		}

		System.out.println("排序后:" + arrayToString(arr));

	}

	// 把数组中的元素按照指定规则组成字符串[元素1,元素2,...]
	public static String arrayToString(int[] arr) {
    
    
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (int i = 0; i < arr.length; i++) {
    
    
			if (i == arr.length - 1) {
    
    
				sb.append(arr[i]);
			} else {
    
    
				sb.append(arr[i]).append(",");
			}

		}
		sb.append("]");
		String s = sb.toString();
		return s;
	}

}

Running results:
insert image description here
Overview and common methods of the Arrays class

The Arrays class contains various methods for manipulating arrays

method name illustrate
public static String toString(int[] a) Returns the character-converted representation of the contents of the specified array
public static void sort(int[] a) Arranges the specified array in numerical order
import java.util.Arrays;

//Arrays类包含用于操作数组的各种方法
//public static String toString(int[] a)   返回指定数组的内容的字符换表示形式|
//public static void sort(int[] a)按照数字顺序排列指定的数组
public class ArraysDemo {
    
    
	public static void main(String[] args) {
    
    
		// 定义一个数组
		int[] arr = {
    
     23, 65, 3, 67, 56 };

		System.out.println("排序前:" + Arrays.toString(arr));
		Arrays.sort(arr);
		System.out.println("排序后:" + Arrays.toString(arr));

	}
}

operation result:
insert image description here

The design idea of ​​the tool class:

  • The construction method is modified with private
  • Members are decorated with public static

Basic type wrapper class

Overview of basic type wrapper classes
The advantage of encapsulating basic data types into objects is that more functional methods can be defined in objects to manipulate the data

One of the commonly used operations: for conversion between basic data types and strings

basic data type Packaging
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

//基本类型包装类
public class IntegerDemo {
    
    
	public static void main(String[] args) {
    
    
		// 需求:要判断一个数据是否在int范围内
		// public static final int MIN_VALUE
		// public static final int MAX_VALUE
		System.out.println(Integer.MIN_VALUE);
		System.out.println(Integer.MAX_VALUE);

	}
}

operation result:
insert image description here

Overview and use of the Integer class

Integer: Wraps the value of the primitive type int in an object

method name illustrate
public Integer(int valve) Create an Integer object from an int value (obsolete)
public Integer(String s) Create Integer objects from String values ​​(obsolete)
public static Integer valueOf(int i) Returns an Integer instance representing the specified int value
public static Integer valueOf(String s) Returns an Integer object String that saves the specified value
//构造方法

// public Integer(int valve)  根据int值创建Integer对象(过时) 
//public Integer(String s)根据String值创建Integer对象(过时)

//静态方法获取对象
//public static Integer valueOf(int i)返回表示指定的int值得Integer实例
//public static Integer valueOf(String s)返回一个保存指定值得Integer对象String

public class IntegerDemo {
    
    
	public static void main(String[] args) {
    
    
//		public Integer(int valve)  根据int值创建Integer对象(过时)
		Integer i1 = new Integer(100);
		System.out.println(i1);
//		public Integer(String s)根据String值创建Integer对象(过时)
		Integer i2 = new Integer(100);
//		Integer i2=new Integer("abc");//NumberFormatException
		System.out.println(i2);

//		public static Integer valueOf(int i)返回表示指定的int值得Integer实例
		Integer i3 = Integer.valueOf(100);
		System.out.println(i3);

//		public static Integer valueOf(String s)返回一个保存指定值得Integer对象String
		Integer i4 = Integer.valueOf("100");// 若写字母,还是会NumberFormatException
		System.out.println(i4);

	}
}

operation result:
insert image description here

Mutual conversion between int and String

The most common operation of the basic type wrapper class is: for conversion between basic types and strings

int to String
public static String valueOf(int i) : Returns the string representation of the int argument. This method is a method in the String class

String is converted to int
public static String parseInt(String s) : parses the string into an int type. This method is a method in the Integer class


//int和String的相互转换
public class IntegerDemo2 {
    
    
	public static void main(String[] args) {
    
    
		// int 转到 String
		int number = 100;
		// 法一
		String s1 = "" + number;// 字符串连接
		System.out.println(s1);
		// 法二 public static String valueOf(int i)
		String s2 = String.valueOf(number);
		System.out.println(s2);
		System.out.println("————————————");

		// String 转到 int
		String s = "100";
		// 法一
		// String---Integer---int
		Integer i = Integer.valueOf(s);
		int x = i.intValue();// public int intValue();
		System.out.println(x);
		// 法二
		// public static int parseInt(String s)
		int y = Integer.parseInt(s);
		System.out.println(y);

	}
}

operation result:
insert image description here

Case: sorting data in a string

Requirements: There is a string: "91 27 46 38 50", please write a program to achieve the final output: "27 38 46 50 91"

import java.util.Arrays;

//字符串中数据排序
//需求:有一个字符串:“91 27 46 38 50”
//请写程序实现最终输出结果是:“27 38 46 50 91”
public class IntegerText {
    
    
	public static void main(String[] args) {
    
    
		// 定义一个字符串
		String s = "91 27 46 38 50";

		// 把字符串中的数据存储到一个int类型的数组中
		// public String[] split(String regex)
		String[] strArray = s.split(" ");
//		for (int i = 0; i < strArray.length; i++) {
    
    
//			System.out.println(strArray[i]);
//		}

		// 定义一个int数组,把String数组中的每个元素存储到int数组中
		int[] arr = new int[strArray.length];
		for (int i = 0; i < arr.length; i++) {
    
    
			// public static int parseInt(String s)
			arr[i] = Integer.parseInt(strArray[i]);
		}

		// 对int数组排序
		Arrays.sort(arr);

		// 把排序后的int数组中的元素拼接得到一个字符串
		// 用StringBuilder实现
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
    
    
			if (i == arr.length - 1) {
    
    
				sb.append(arr[i]);
			} else {
    
    
				sb.append(arr[i]).append(" ");
			}
		}
		String result = sb.toString();
		// 输出结果
		System.out.println(result);
	}
}

operation result:
insert image description here

Automatic boxing and unboxing

  • Boxing: convert the basic data type to the corresponding wrapper class type
  • Unboxing: convert the wrapper class type to the corresponding basic data type
//装箱:把基本数据类型转换为对应的包装类类型

//拆箱:把包装类类型转换为对应的基本数据类型

public class IntegerDemo3 {
    
    
	public static void main(String[] args) {
    
    
		// 装箱:把基本数据类型转换为对应的包装类类型
		Integer i = Integer.valueOf(100);
		// 自动装箱
		Integer ii = 100;// Integer.valueOf(100)

		// 拆箱:把包装类类型转换为对应的基本数据类型
		// ii+=200;
		// 手动拆箱:ii.intValue()
//		ii=ii.intValue()+200;
		// 自动拆箱
		ii += 200;
		System.out.println(ii);

		Integer iii = null;
//		iii+=300;//NullPointerException
		if (null != iii) {
    
    
			iii += 300;
		}
	}
}

Note:
When using the wrapper class type, if you do an operation, it is best to first determine whether it is null.
As long as it is an object, it must be judged that it is not null before use

Guess you like

Origin blog.csdn.net/weixin_47678894/article/details/119070471