数字基本数据类型的封装类
数字的基本数据类型都有一个对应的封装类(将基本数据类型转化成对象),对应如下:
| 基本数据类型 | 封装类 | 
|---|---|
| int | Integer | 
| byte | Byte | 
| double | Double | 
| short | Short | 
| float | Float | 
| long | Long | 
基本数据类型和封装类的转换
int x = 5;//基本数据类型Integer X = new Integer(x);//基本数据类型转化为封装类int x1 = X.intValue();//封装类转基本数据类型
自动装箱与拆箱
每次都要新建类或者调用方法太累了,好在 Java 提供了自动装箱/拆箱 功能,可以简化我们的操作。
int x = 5;//两者可以自由赋值,转换Integer X = x;int x1 = X;
数字和字符串的相互转换
下面的例子都是基于 int,但是别的数据类型也差不多,可以照葫芦画瓢。
数字转字符串
int x = 31415927;//方法1String s1 = String.valueOf(x);//方法2String s2 = new Integer(x).toString();//由于装箱拆箱的概念,所以 new Integer 这种新建对象的形式好像从 JDK9 开始被废弃了//如果用不了,还是分两行写吧
字符串转数字
String s = "31415927";int x = Integer.parseInt(s);
Math类 常用方法与常量
public class Main {public static void main(String[] args) {// 5.4四舍五入即5System.out.println(Math.round(5.4));// 5.5四舍五入即6System.out.println(Math.round(5.5));//最大值System.out.println(Math.max(5.4, 5.5));//最小值System.out.println(Math.min(5.4, 5.5));//绝对值System.out.println(Math.abs(-3.1415926));//三角函数System.out.println(Math.sin(Math.PI / 3));System.out.println(Math.cos(Math.PI / 3));System.out.println(Math.tan(Math.PI / 3));// 得到一个0-1之间的随机浮点数(取不到1)System.out.println(Math.random());// 得到一个0-10之间的随机整数 (取不到10)System.out.println((int) (Math.random() * 10));// 开方System.out.println(Math.sqrt(9));// n次方(2的4次方)System.out.println(Math.pow(2, 4));// πSystem.out.println(Math.PI);// 自然常数eSystem.out.println(Math.E);}}
