第二阶段 day07 【Object类、常用API】
主要内容
- Object类
- Date类
- DateFormat类
- Calendar类
- System类
- StringBuilder类
- 包装类
教学目标
-[ ] 能够说出Object类的特点
-[ ] 能够重写Object类的toString方法
-[ ] 能够重写Object类的equals方法
-[ ] 能够使用日期类输出当前日期
-[ ] 能够使用将日期格式化为字符串的方法
-[ ] 能够使用将字符串转换成日期的方法
-[ ] 能够使用System类的数组复制方法
-[ ] 能够使用System类获取当前毫秒时刻值
-[ ] 能够说出使用StringBuilder类可以解决的问题
-[ ] 能够使用StringBuilder进行字符串拼接操作
-[ ] 能够说出8种基本类型对应的包装类名称
-[ ] 能够说出自动装箱、自动拆箱的概念
-[ ] 能够将字符串转换为对应的基本类型
-[ ] 能够将基本类型转换为对应的字符串
第一章 Object类
1.1 概述
java.long.Object 是java语言中的根类,即所有类的父类。它中描述的所有方法子类都可以使用。在对象实例化的时候,最终找的父类就是Object。
如果一个类没有特别指定父类, 那么默认则继承自Object类。例如:
public class MyClaa /* extends Objext */ {
// ...
}
根据JDK源代码及Object类的API文档,Object类当中包含的方法有11个。今天我们主要学习其中的2个:
public String toString()
:返回该对象的字符串表示。public boolean equals(Object obj)
:指示其他某个对象是否与此对象“相等”。
1.2 toString方法
方法摘要
public String toString()
:返回该对象的字符串表示。
toString方法返回该对象的字符串表示,其实该字符串内容就是对象的类型+@+内存地址值。
由于toString方法返回的结果是内存地址,而在开发中,经常需要按照对象的属性得到相应的字符串表现形式,因此也需要重写它。
覆盖重写
如果不希望使用toString方法的默认行为,则可以对它进行覆盖重写。例如自定义的Person类:
package cn.witty.obj.demo01obj;
public class Person {
private String name;
private int age;
// 重写toString方法
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
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;
}
}
在IntelliJ IDEA中,可以点击Code
菜单中的Generate...
,也可以使用快捷键alt+insert
,点击toString()
选项。选择需要包含的成员变量并确定。
小贴士: 在我们直接使用输出语句输出对象名的时候,其实通过该对象调用了其toString()方法。
1.3 equals方法
方法摘要
public boolean equals(Object obj)
:指示其他某个对象是否与此对象“相等”。
调用成员方法equals并指定参数为另一个对象,则可以判断这两个对象是否是相同的。这里的“相同”有默认和自定义两种方式。
默认地址比较
如果没有覆盖重写equals方法,那么Object类中默认进行==
运算符的对象地址比较,只要不是同一个对象,结果必然为false。
对象内容比较
如果希望进行对象的内容比较,即所有或指定的部分成员变量相同就判定两个对象相同,则可以覆盖重写equals方法。例如:
package cn.witty.obj.demo02equals;
import java.util.Objects;
public class Person {
private String name;
private int age;
@Override
public boolean equals(Object o) {
// 如果对象地址一样,则认为相同
if (this == o) return true;
// 如果参数为空,或者类型信息不一样,则认为不同
if (o == null || getClass() != o.getClass()) return false;
// 转换为当前类型
Person person = (Person) o;
// 要求基本类型相等,并且将引用类型交给java.util.Objects类的equals静态方法取用结果
return age == person.age &&
Objects.equals(name, person.name);
}
}
这段代码充分考虑了对象为空、类型一致等问题,但方法内容并不唯一。大多数IDE都可以自动生成equals方法的代码内容。在IntelliJ IDEA中,可以使用Code
菜单中的Generate…
选项,也可以使用快捷键alt+insert
,并选择equals() and hashCode()
进行自动代码生成。
tips:Object类当中的hashCode等其他方法,今后学习。
1.4 Objects类
在刚才IDEA自动重写equals代码中,使用到了java.util.Objects
类,那么这个类是什么呢?
在JDK7添加了一个Objects工具类,它提供了一些方法来操作对象,它由一些静态的实用方法组成,这些方法是null-save(空指针安全的)或null-tolerant(容忍空指针的),用于计算对象的hashcode、返回对象的字符串表示形式、比较两个对象。
在比较两个对象的时候,Object的equals方法容易抛出空指针异常,而Objects类中的equals方法就优化了这个问题。方法如下:
-
public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); }
1.5 native本地方法
在Object类的源码中定义了 native 修饰的方法, native 修饰的方法称为本地方法。
- 本地方法的作用: 就是Java调用非Java代码的接口。方法的实现由非Java语言实现,比如C或C++。
- 当我们需要访问C或C++的代码时,或者访问操作系统的底层类库时,可以使用本地方法实现。
也就意味着Java可以和其它的编程语言进行交互。
Object类源码(部分):
package java.lang;
/**
* Class {@code Object} is the root of the class hierarchy.
* Every class has {@code Object} as a superclass. All objects,
* including arrays, implement the methods of this class.
*
* @author unascribed
* @see java.lang.Class
* @since JDK1.0
*/
public class Object {
// 本地方法
private static native void registerNatives();
// 静态代码块
static {
registerNatives();
}
............
}
第二章 日期时间类
2.1 Date类
概述
java.util.Date
类 表示特定的瞬间,精确到毫秒。
继续查阅Date类的描述,发现Date拥有多个构造函数,只是部分已经过时,但是其中有未过时的构造函数可以把毫秒值转成日期对象。
-
public Date():分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
-
public Date(long date):分配Date对象并初始化此对象,以表示 从标准基准时间(称为“历元(epoch)”,即1970年1月1日00:00:00 GMT)以来的指定毫秒数。
tips: 由于我们处于东八区,所以我们的基准时间为1970年1月1日8时0分0秒。
简单来说:使用无参构造,可以自动设置当前系统时间的毫秒时刻;指定long类型的构造参数,可以自定义毫秒时刻。例如:
package cn.witty.obj.demo03date;
import java.util.Date;
public class Demo01Date {
public static void main(String[] args) {
// 创建日期对象,当前时间
System.out.println(new Date()); // Fri Jul 24 12:19:55 CST 2020
// 创建日期对象,把当前的毫秒值转换为日期对象
System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970
}
}
tips:在使用println方法时,会自动调用Date类中的toString方法。Date类对Object类中的toString方法进行了覆盖重写,所以结果为指定格式的字符串。
常用方法
Date类中的多数方法已经过时,常用的方法有:
-
public long getTime(): 把日期对象转化为对应的时间毫秒值
2.2 DateFormat类
java.text.DateFormat
是日期/时间格式化子类的抽象类,我们通过这个类可以帮我们完成日期和文本之间的转换,也就是可以在Date对象与String对象之间进行来回转换。
- **格式化:**按照指定格式,从Date对象转化为String对象
- 解析:按照指定格式,从String 对象转化为Date对象。
构造方法
由于DateFormat为抽象类,不能直接使用,所以需要常用的子类java.text.SimpleDateFormat
。这个类需要一个模式(格式)来指定格式化或解析的标准。构造方法为:
-
public SimpleDateFormat(String patten):用给定的模式和默认语言环境的日期格式符号构造SimpleDateFormat。
参数pattern是一个字符串,代表日期时间的自定义格式。
常用的标识符规则为:
表示字母(区分大小写) | 含义 |
---|---|
y | 年 |
M | 月 |
d | 日 |
H | 时 |
m | 分 |
s | 秒 |
备注:更详细的格式规则,可以参考SimpleDateFormat类的API文档0。
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Demo02ImpleDateFormat {
public static void mian(String[] args) {
// 对应的日期格式:2020-01-19 17:06:23
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
}
}
常用方法:
DateFormat类常用方法有:
-
public String format(Date date):将Date对象转化为字符创格式
-
public Date parse(String source):将字符串解析为Date时间类型对象
format方法:
使用format方法的代码:
package cn.witty.obj.demo03date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
讲Date对象转换为String字符串
*/
public class Demo02SimpleDateFormat {
public static void main(String[] args) {
Date date = new Date();
// 对应的日期格式:yyyy-MM-dd HH:mm:ss
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将Date对象转化String字符串
String str = dt.format(date);
System.out.println(str); // 2020-07-24 14:11:59
}
}
parse方法:
使用parse方法的代码如下:
package cn.witty.obj.demo03date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
把String 转换为Date对象
*/
public class Demo03DateFormatMethod {
public static void main(String[] args) throws ParseException {
// 设置时间格式
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 获取当前是时间
Date date1 = new Date();
System.out.println(date1);
// 设置当前时间为字符串格式
String str = df.format(date1);
System.out.println(str);
// 将字符串转化为Date类型
Date date = df.parse(str);
System.out.println(date); // Sun Jan 19 00:00:00 CST 2020
}
}
2.3 练习
请使用日期时间相关的API,计算出一个人已经出生了多少天。
思路:
1.获取当前时间对应的毫秒值
2.获取自己出生日期对应的毫秒值
3.两个时间相减(当前时间– 出生日期)
代码实现:
package cn.witty.obj.demo03date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/*
## 2.3 练习
请使用日期时间相关的API,计算出一个人已经出生了多少天。
**思路:**
*/
public class Demo05Test {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
// 1 请用户输入自己的生日
System.out.println("请输入出生日期:yyyy-MM-dd");
String str = sc.nextLine();
// 2 将str字符串时间转换为Date时间,再转化为毫秒值
// 2.1 设置时间格式
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// 2.2 将生日时间转换为date格式
Date date1 = df.parse(str);
// 2.3 将Date类型的出生日期转换为毫秒值
long time1 = date1.getTime();
// 3 获取当前时间
Date date = new Date();
// 3/1转化当前时间格式为毫秒值
long time2 = date.getTime();
// 4 进行运算得出当前时间与实际时间的天数进行输出
// 判断
long time = (time2 - time1);
if (time <= 0) {
System.out.println("对不起,还未出生呢!!!");
} else {
System.out.println((time/1000/60/60/24) + " 天。");
}
}
}
2.4 Calendar类
概念
日历我们都见过
java.util.Calendar 是日历类,在Date后出现,替换掉许多Date的方法。该类将所有可能用到的时间信息封装为静态成员变量,方便获取。日历类就是方便获取各个时间属性的。
获取方式
Calendar为抽象类,由于语言敏感性,Calendar类在创建对象时并非直接创建,而是铜鼓静态方法创建,返回子类对象,如下:
Calendar静态方法:
-
public static Calendar getInstance():使用默认时区和语言环境获取一个日历。
例如:
package cn.witty.obj.demo05Calendar;
import java.util.Calendar;
public class Demo01Calendar {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
}
}
常用方法:
根据Calendar类的API文档,常用方法有:
-
public int get(int field):返回值给定日历字段的值
-
public void set(int field, int value):将给定的日历字段设置为给定值。
-
public abstract void add(int field, int amout) :根据日历的规则,将给定的日历字段添加或者减去指定的时间量。
-
public Date getTime():返回一个表示此Calendar时间值,(从历元到现在的毫秒偏移量)的Date对象。
-
Calendar类中提供很多成员常量,代表给定的日历字段:
字段值 | 含义 |
---|---|
YEAR | 年 |
MONTH | 月(从0开始,可以+1使用) |
DAY_OF_MONTH | 月中的天(几号) |
HOUR | 时(12小时制) |
HOUR_OF_DAY | 时(24小时制) |
MINUTE | 分 |
SECOND | 秒 |
DAY_OF_WEEK | 周中的天(周几,周日为1,可以-1使用) |
get/set方法
get方法用来获取指定字段的值,set方法用来设置指定字段的值,代码使用演示:
注意:先设置,后获取。设置的字段值,例如:
// 设置月
cal.set(Calendar.MONTH, 9);
package cn.witty.obj.demo05Calendar;
import java.util.Calendar;
public class CalendarUtil {
public static void main(String[] args) {
// 创建Calendar对象
Calendar cal = Calendar.getInstance();
// 获取年
int year = cal.get(Calendar.YEAR);
// 设置月
cal.set(Calendar.MONTH, 9);
// 获取月
int month = cal.get(Calendar.MONTH) + 1;
// 获取日 设置日
cal.set(Calendar.DAY_OF_MONTH, 13);
int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
// 输出
System.out.println(year + " 年 " + month + " 月 " + day_of_month + " 日 ");
}
}
第二种设置方法:
package cn.witty.obj.demo05Calendar;
import java.time.Year;
import java.util.Calendar;
public class Demo02Calendar {
public static void main(String[] args) {
// 创建Calendar对象
Calendar cal = Calendar.getInstance();
// 获取年
int year = cal.get(Calendar.YEAR);
// 获取月
int month = cal.get(Calendar.MONTH) + 1;
// 获取日
int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
// 设置年
cal.set(Calendar.YEAR, 2011);
// 输出
System.out.println(cal.get(Calendar.YEAR) + " 年 " + month + " 月 " + day_of_month + " 日 ");
}
}
add方法
add方法可以对指定日历字段的值进行加减操作,如果第二个参数为正数则加上偏移量,如果为负数减去偏移量。代码如下:
package cn.witty.obj.demo05Calendar;
import java.util.Calendar;
public class Demo03CalendarAdd {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year + " 年 " + month + " 月 " + day_of_month + " 日 ");
// 使用add方法
cal.add(Calendar.DAY_OF_MONTH, -3); // 减少3天
cal.add(Calendar.YEAR, -3); // 减少3年
int year1= cal.get(Calendar.YEAR);
int month1 = cal.get(Calendar.MONTH) + 1;
int day_of_month1 = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year1 + " 年 " + month1 + " 月 " + day_of_month1 + " 日 ");
}
}
getTime方法:
package cn.witty.obj.demo05Calendar;
import java.util.Calendar;
import java.util.Date;
public class Demo04GetTime {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
System.out.println(date); // Sat Jul 25 15:27:22 CST 2020
}
}
小贴士:
西方星期的开始为周日,中国为周一。
在Calendar类中,月份的表示是以0-11代表1-12月。
日期是有大小关系的,时间靠后,时间越大。
第三章 System类
java.lang.System类中提供了大量的静态方法,可以活动与系统相关的信息和系统级操作。在System类的API文档中。常用的方法有:
-
public static long currentTimeMillis() : 返回以毫秒值为单位的时间。
-
public static void arraycopy(Object src, int srcPos, Object dest, Object destPos, int length):将数组指定的数据拷贝到另一个数组中。
3.1 currentTimeMillis 方法
实际上,currentTimeMillis方法就是获取当前时间与1970年01月01日00:00点的时间毫秒值:
package cn.witty.obj.demo05Calendar;
public class Demo05currentTimeMillis {
public static void main(String[] args) {
// 获取当前时间的毫秒值
System.out.println(System.currentTimeMillis()); // 1595662703574
}
}
练习
验证for循环打印数字1-9999所需要使用的时间(毫秒)
package cn.witty.obj.demo05Calendar;
/*
### 练习
验证for循环打印数字1-9999所需要使用的时间(毫秒)
*/
public class Demo06Test2 {
public static void main(String[] args) {
// 获取当前时间
long l1 = System.currentTimeMillis();
//打印1-9999
for (int i = 1; i <= 9999; i++) {
System.out.println(i);
}
// 结束时间
long l2 = System.currentTimeMillis();
// 计算时间:
long l = (l2 - l1);
// 打印
System.out.println(l + " 毫秒。");
}
}
3.2 arraycopy方法
-
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) :将数组中指定的数据拷贝到另一个数组中。
数组的拷贝动作是系统级的,性能很高,System.arraycopy 方法具有4个参数:含义分别是。
参数序号 | 参数名称 | 参数类型 | 参数含义 |
---|---|---|---|
1 | src | Object | 源数组 |
2 | srcPos | int | 源数组索引起始位置 |
3 | dest | Object | 目标数组 |
4 | destPos | int | 目标数组索引起始位置 |
5 | length | int | 复制元素个数 |
练习:
将src数组中前3个元素,复制到dest数组的前3个位置,src数组元素[1,2,3,4,5],dest数组元素[6,7,8,9,10]复制元素后:src数组元素[1,2,3,4,5],dest数组元素[1,2,3,9,10]
package cn.witty.obj.demo05Calendar;
/*
#### 练习:
将src数组中前3个元素,复制到dest数组的前3个位置,src数组元素[1,2,3,4,5],
dest数组元素[6,7,8,9,10]复制元素后:src数组元素[1,2,3,4,5],
dest数组元素[1,2,3,9,10]
*/
public class Demo07Test {
public static void main(String[] args) {
// 设置原数组src
int[] src = {1, 2, 3, 4, 5};
// 目标数组dest
int[] dest = {6, 7, 8, 9, 10};
// 使用arraycopy拷贝数组
// (原数组, 起始位置, 目标数组, 起始位置, 拷贝替换个数);
System.arraycopy(src, 0, dest, 0, 3);
// 遍历输出dest
for (int i = 0; i < dest.length; i++) {
System.out.print(dest[i] + " ");
}
}
}
第四章 Math类
4.1 概述
- java.lang.Math(类):Math包含执行基本数字运算的方法。
- 它不能创建对象,它的构造方法被 私有了。因为它的内部都是 静态方法 ,通过类名直接调用即可。
4.2 常用方法
方法名 | 说明 |
---|---|
public static int abs(int a ) | 说明参数的绝对值 |
public static double ceil(double a) | 向上取整数 |
public static double floor(double a) | 向下取整数 |
public static double pow(double a, double b) | 获取a的b次幂 |
public static long round(double a) | 四舍五入取整数 |
4.3 示例代码
package cn.witty.obj.demo06Math;
/*
| 方法名 | 说明 |
| -------------------------------------------- | ---------------- |
| public static int abs(int a ) | 说明参数的绝对值 |
| public static double ceil(double a) | 向上取整数 |
| public static double floor(double a) | 向下取整数 |
| public static double pow(double a, double b) | 获取a的b次幂 |
| public static long round(double a) | 四舍五入取整数 |
*/
public class Demo01Math {
public static void main(String[] args) {
System.out.println("-5 绝对值:" + Math.abs(-5)); // 5
System.out.println("-3.63 绝对值:" + Math.abs(-3.63)); //3.63
System.out.println("3.5 向上取整数: " + Math.ceil(3.5)); // 4.0
System.out.println("-3.5 向上取整数:" + Math.ceil(-3.5)); // -3.0
System.out.println("3.49 向下取整:" + Math.floor(3.49)); // 3.0
System.out.println("获取 3.1 的 3 幂次方:" + Math.pow(3.1, 3)); // 29.791000000000004
System.out.println("四舍五入取得整数:" + Math.round(3.49)); // 3
}
}
第五章 BigInteger类
5.1 概述
java.math.BigInteger 类,不可变的任意精度的整数。如果运算中,数据的范围超过了long类型后,可以使用BigInteger类实现,该类的计算整数是不限制长度的。
5.2 构造方法
BigInteger(String value) 将 BigInteger 的十进制字符串表示形式转换为 BigInteger。超过long类型的范围,已经不能称为数字了,因此构造方法中采用字符串的形式来表示超大整数,将超大整数封装成BigInteger对象。
5.3 成员方法
BigInteger类提供了对很大的整数进行加、减、乘、除的方法,注意:都是与另一个BigInteger对象进行运算。
方法声明 | 描述 |
---|---|
add(BigInteger value) | 返回其值为(this + val)的BigInteger,超大整数加法运算。 |
subtract(BigInteger value) | 返回其值为(this - val)的BigInteger ,超大整数减法运算。 |
multiply(BigInteger value) | 返回其值为(this * val)的BigInteger ,超大整数乘法运算。 |
divide(BigInteger value) | 返回其值为(this / val)的BigInteger,超大整数除法运算。 |
示例:
package cn.witty.obj.demo07BigInteger;
import java.math.BigInteger;
/*
| 方法声明 | 描述 |
| ---------------------------- | --------------------------------------------------------- |
| add(BigInteger value) | 返回其值为(this + val)的BigInteger,超大整数加法运算。 |
| subtract(BigInteger value) | 返回其值为(this - val)的BigInteger ,超大整数减法运算。 |
| multiply(BigInteger value) | 返回其值为(this * val)的BigInteger ,超大整数乘法运算。 |
| divide(BigInteger value) | 返回其值为(this / val)的BigInteger,超大整数除法运算。 |
*/
public class Demo01BigInteger {
public static void main(String[] args) {
BigInteger big1 = new BigInteger("200000000000000000");
BigInteger big2 = new BigInteger("100000000000000000");
// 加法
BigInteger add = big1.add(big2);
System.out.println(add); // 300000000000000000
// 减法
BigInteger subtract = big1.subtract(big2);
System.out.println(subtract); // 100000000000000000
// 乘法
BigInteger multiply = big1.multiply(big2);
System.out.println(multiply); // 20000000000000000000000000000000000
// 除法
BigInteger divide = big1.divide(big2);
System.out.println(divide); // 2
}
}
第六章 BigDecimal类
6.1 引入
使用基本类型做浮点数运算精度问题;
看程序说结果:
package cn.witty.obj.dmeo08BigDecimal;
public class Demo01BigDecimal {
public static void main(String[] args) {
System.out.println(0.09 + 0.01); //0.09999999999999999
System.out.println(1.0 - 0.32); // 0.6799999999999999
System.out.println(1.015 * 100); // 101.49999999999999
System.out.println(1.301 / 100); // 0.013009999999999999
}
}
对于浮点运算,不要使用基本类型,而使用"BigDecimal类"类型
6.2 概述
相关内容 | 具体描述 |
---|---|
包 | java.math 使用时需要导包 |
类声明 | public class BigDecimal extends Number implements Comparable |
描述 | BigDecimal类提供了算术,缩放操作,舍入,比较,散列和格式转换的操作。提供了更加精准的数据计算方式 |
6.3 构造方法
构造方法名 | 描述 |
---|---|
BigDecimal(double val) | 将double类型封装为BigDecimal对象 |
BigDecimal(String val) | 将BigDecimal 的字符串表示转化为 BigDecimal |
注意:推荐使用第二种方式,第一种存在精度问题;
6.4 常用方法
BigDecimal类中使用最多的还是提供的进行四则运算的方法,如下:
方法声明 | 描述 |
---|---|
public BigDecimal add(BigDecimal value) | 加法运算 |
public BigDecimal subtract(BigDecimal value) | 减法运算 |
public BigDecimal multiply(BigDecimal value) | 乘法运算 |
public BigDecimal divide(BigDecimal value) | 除法运算 |
注意:对于divide方法来说,如果除不尽的话,就会出现java.lang.ArithmeticException异常。此时可以使用
divide方法的另一个重载方法;
BigDecimal divide(BigDecimal divisor, int scale, int roundingMode): divisor:除数对应的BigDecimal对象; 参数说明:scale:精确的位数;roundingMode取舍模式
小结:Java中小数运算有可能会有精度问题,如果要解决这种精度问题,可以使用BigDecimal
第七章 包装类
7.1 概述
Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类,如下
基本类型 | 对应的包装类(位于java.lang包中) |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
7.2 Integer类
- Integer类概述 :包装一个对象的基本类型为int的类
- Integer类构造方法及静态方法
方法名 | 说明 |
---|---|
public Integer(int value) | 根据 int 值创建 Integer 对象(过时) |
public Integer(String s) | 根据 String 值创建 Integer 对象(过时) |
public static Integer valueOf(int i) | 返回表示指定的 int 值的 Integer 实例 |
public static Integer valueOf(String s) | 返回保存指定String值的 Integer 对象 |
- 示例代码
package cn.witty.obj.demo09Integer;
/*
| 方法名 | 说明 |
| --------------------------------------- | ------------------------------------- |
| public Integer(int value) | 根据 int 值创建 Integer 对象(过时) |
| public Integer(String s) | 根据 String 值创建 Integer 对象(过时) |
| public static Integer valueOf(int i) | 返回表示指定的 int 值的 Integer 实例 |
| public static Integer valueOf(String s) | 返回保存指定String值的 Integer 对象 |
*/
public class IntegerDemo {
public static void main(String[] args) {
// | public Integer(int value) | 根据 int 值创建 Integer 对象(过时) |
Integer integer1 = new Integer(100);
System.out.println(integer1);
// | public Integer(String s) | 根据 String 值创建 Integer 对象(过时) |
Integer integer2 = new Integer("100");
System.out.println(integer2);
// | public static Integer valueOf(int i) | 返回表示指定的 int 值的 Integer 实例 |
Integer integer3 = Integer.valueOf(100);
System.out.println(integer3);
// | public static Integer valueOf(String s) | 返回保存指定String值的 Integer 对象 |
Integer integer4 = Integer.valueOf("100");
System.out.println(integer4);
}
}
7.3 装箱与拆箱
基本类型和对应的包装类对象之间,来回转换的过程称之为 装箱 与 拆箱
-
装箱: 从基本类型转换为对应的包装类类型
-
拆箱: 从包装类类型转换为对应的基本类型
用Integer与int为例:
基本类型 – >包装类型
Integer i = Integer.valueOf(10); // 使用包装类的valueOf方法
-
包装类 – > 基本数值
int num = i.intVlaue();
7.4 自动装箱与自动拆箱
由于我们经常要做基本类型与包装类之间的转换,从Java 5(JDK 1.5)开始,基本类型与包装类的装箱、拆箱动作
可以自动完成。例如:
Integer i = 4; // 自动装箱,相当于 Integer i = Integer.valueOf(4);
i = i + 5; // 等号右边:将i对象转成基本类型(自动拆箱)相当于: i.intValue() + 5;
7.5 基本类型与字符串之间的转换
基本类型转换为String
- 转换方式
- 方式一 : 直接在数字后面加一个空字符串
- 方式二:通过String类静态方法valueOf()
- 示例代码:
package cn.witty.obj.demo10String;
public class Demo01String {
public static void main(String[] args) {
// int -- String
int num = 100;
// 方式一
String str = num + "";
System.out.println(str);
// 方式二 public static String valueOf(int i)
String str2 = String.valueOf(num);
System.out.println(str2);
System.out.println("--------------");
}
}
String 类型转换为基本类型:
除了Character类之外,其他所有包装类都具有parseXXX静态方法可以将字符串转化为对应的基本数据类型。
-
public static byte parseByte(String s):将字符串类型转化为对应的byte基本类型
-
public static short parseShort(String s):将字符串类型转化为对应的short基本类型
-
public static int parseInteger(String s): 将字符串类型转化为对应的int基本类型
-
public static long parseLong(String s):将字符串类型转化为对应的long类型
-
public static float parseFloat(String s) :将字符串参数转换为对应的float基本类型。
-
public static double parseDouble(String s) :将字符串参数转换为对应的double基本类型。
-
public static boolean parseBoolean(String s) :将字符串参数转换为对应的boolean基本类型。
代码使用(仅以Integer类的静态方法parseXxx为例)如:
- 转换方式
- 方式一:先将字符串数字转成Integer,再调用valueOf()方法。
- 方法二: 通过Integer静态方法parseInt()进行转换
示例代码:
package cn.witty.obj.demo10String;
public class IntegerDemo {
public static void main(String[] args) {
// String -- int
String s = "100";
// 方式一:先将字符串数字转成Integer,再调用valueOf()方法
Integer num = Integer.valueOf(s);
// 再调用valueOf()方法
int i = num.intValue();
System.out.println(i);
// 方式二:通过Integer静态方法parseInt()进行转化
int i1 = Integer.parseInt(s);
System.out.println(i1);
}
}
注意:如果字符串参数的内容无法正确转换为对应的基本类型,则会抛出
java.lang.NumberFormatException 异常。