【JavaSE 第十四天】
一、 String 相关的内容
1. 字符串出现的次数
有一个字符串 A,另一个字符串 B,计算 B 字符串在 A 字符串中出现几次
例子 : A 字符串:dsabdnabdsnabeabiwpabekabd B 字符串:ab
- 实现过程
- ①对字符串进行索引查找 indexOf
- ②一旦找到一个,计数器++
- ③找到的字符串的索引记录,进行字符串的截取
- ④直到找不到为止,indexOf 方法结果是 -1 时
public static void main(String[] args) {
String str="sdfabghiouabsjabisabab";
String sub="ab";
int count = stringCount(str,sub);
System.out.println("count = " + count);
}
/**
* @param str 原始字符串
* @param sub 要查找的字符串
* @return 出现次数
*/
public static int stringCount(String str ,String sub){
// 定义变量,计数器
int count = 0;
// 定义变量,记录字符串查找后的索引
int index = 0;
// 对字符串出现的位置,进行查询
// 反复查找,使用循环while
// 循环条件就是 indexOf 方法返回 -1
while ( (index=str.indexOf(sub)) != -1 ) {
// 执行了循环 index !=-1 字符串出现了
count ++;
// 截取字符串,开始索引 (index + 被查找字符串的长度)
str = str.substring(index + sub.length());
}
return count;
}
2. 哪个字符出现的最多
要求:指定字符串只能是(小写或大写)字母(并且大小写一致),例如: abeegewff,计算出哪个字符出现的次数最多
局限性:限定字符串中字母只能有26个,每个字母的计数器属于自己,不能换位置,否则计数不正确
找每个字符各自出现多少次,找出最大值
- 实现过程 :
- ①字符串转成数组 (单个字符操作)
- ②创建长度为26的数组,用作计数器使用
- ③取出数组中的字符,(字符 - 97) 为了对应数组的索引,之后计数器++
- ④找出数组中的最大值
// 在类之外还需要导入 import java.util.Arrays;
public static void main(String[] args) {
char ch=charCount("aabbbbbbcdeeeef");
System.out.println("ch = " + ch);
}
/**
* 查找字符串中,哪个字符出现的次数最多
* @param str 要查找字符串
* @return 返回出现次数最多的字符
*/
public static char charCount(String str){
// 字符串转成数组
char[] chars = str.toCharArray();
// 定义26长度的数组,保存每个字符出现的次数
int[] count = new int[26];
// 遍历数组
for (int i = 0 ; i < chars.length; i++){
// 取出单个字符
char ch = chars[i];
// 字符 - 97 作为数组的索引使用 (这个数组是计数器数组)
count[ ch - 97 ] ++;
}
System.out.println("Arrays.toString(count) = " + Arrays.toString(count));
//利用这种方式遍历数组,并且通过这种方式测试具体个数
// 取出count数组中的,最大值的索引
int index = 0 ; // 数组最大值的索引
int max = count[0];
for(int i = 1 ; i < count.length ; i++){
if (max < count[i]){
index = i;
max = count[i];
}
}
// index索引,正好和字符相差 97
return (char) (index+97);
}
二、 大数运算
基本数据类型 long ,double 都是有取值范围的数据类型,但是当遇到超过范围数据时,Java 引入了大数运算对象, 在 Java 中超过取值范围的数据,不能称为数字,而是称为对象(运算精度高)
java.math 包中具有:BigInteger 大整数 、BigDecimal 大浮点数(高精度,不损失精度)
- BigInteger 类使用,计算超大整数:
- 创建大数据运算对象直接
new BigInteger(String str)
数字格式的字符串,长度任意,支持正负数 BigInteger add(BigInteger b)
计算两个 BigInteger 的数据求和BigInteger subtract(BigInteger b)
计算两个 BigInteger 的数据求差BigInteger multiply(BigInteger b)
计算两个 BigInteger 的数据求乘积BigInteger divide(BigInteger b)
计算两个 BigInteger 的数据求商,结果会截掉小数
- 创建大数据运算对象直接
public static void main(String[] args) {
// 创建大数据运算对象
BigInteger b1 = new BigInteger("2345673456786554678996546754434343244568435678986");
BigInteger b2 = new BigInteger("8765432345678987654323456787654");
// b1 + b2 求和
BigInteger add = b1.add(b2);
System.out.println("add = " + add);
// b1 - b2 求差
BigInteger subtract = b1.subtract(b2);
System.out.println("subtract = " + subtract);
// b1 * b2 求积
BigInteger multiply = b1.multiply(b2);
System.out.println("multiply = " + multiply);
// b1 / b2 求商,结果会截掉小数
BigInteger divide = b1.divide(b2);
System.out.println("divide = " + divide);
}
- BigDecimal 类使用,计算超大浮点数
- 构造方法,和 BigInteger 一样
- 方法 + (加法) - (加法) * (乘法) 和 BigInteger 一样
BigDecimal divide
除法运算divide(BigDecimal big,int scalar,int round)
方法有三个参数:- big 是被除数
- scalar 是保留几位
- round 是保留方式
- 保留方式:参看该类的静态成员变量(字段摘要):(静态类名成员,类名直接调用)
BigDecimal.ROUND_UP
不管四舍五入,直接向上进一位BigDecimal.ROUND_DOWN
直接舍去BigDecimal.ROUND_HALF_UP
四舍五入
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("3.55");
BigDecimal b2 = new BigDecimal("2.12");
System.out.println(b1.add(b2)); // 加法
System.out.println(b1.subtract(b2)); // 减法
System.out.println(b1.multiply(b2)); // 乘法
// 计算 b1 / b2
/**
* 除不尽就会出现异常
* 高精度运算,不能产生无序循环小数,无限不循环小数
* 必须规定保留几位小数、保留方式:
*
* BigDecimal.ROUND_UP 不管四舍五入,直接向上进一位
* BigDecimal.ROUND_DOWN 直接舍去
* BigDecimal.ROUND_HALF_UP 四舍五入
*/
BigDecimal divide = b1.divide(b2,3,BigDecimal.ROUND_HALF_UP);
System.out.println("divide = " + divide);
}
三、 日期和日历类
1. Date
表示当前的日期对象,精确到毫秒值,java.util.Date 类
-
构造方法:
- 无参数构造方法:
new Date()
- 有 long 型参数的构造方法:
new Date(long 毫秒值)
- 无参数构造方法:
-
Date 类没有过时的方法:(绝大部分都过时了)
long getTime()
返回当前日期对应的毫秒值void setTime(long 毫秒值)
日期设定到毫秒值上
/**
* 1.创建对象,使用无参数的构造方法
*/
public static void date1(){
Date date = new Date();
// 返回当前系统时间
System.out.println("date = " + date);
}
/**
* 2.创建对象,使用有参数的构造方法
*/
public static void date2(){
Date date = new Date(0); // 传递毫秒值
// 输出该毫秒值下的具体时间
System.out.println("date = " + date);
}
/**
* 3. getTime()
* 4. setTime()
*/
public static void date3(){
Date date = new Date();
// 获取毫秒值
long time = date.getTime();
// 返回一个 long 数据类型的参数
System.out.println(time);
// 设置日期
date.setTime(0);
System.out.println(date);
}
2. Date 类中最重要内容
-
日期对象和毫秒值之间的相互转换:
-
日期对象,转成毫秒值:
new Date().getTime()
System.currentTimeMillis()
-
毫秒值转成日期对象:
new Date(毫秒值)
new Date().setTime(毫秒值)
转换的意义:日期是特殊的数据,不能数学计算,但是毫秒值可以数学计算。
24*60*60*1000
是一天的毫秒值
3. 日历类 Calendar
日历类:java.util.Calendar
日历字段:组成日历的每个部分,都称为日历字段:年、月、日、时、分、秒、星期
Calendar 是抽象类,不能建立对象,所以需要子类继承:GregorianCalendar (格林威治日历)
(1) 获取 Calendar 类的对象
由于创建日历对象的过程非常的繁琐:考虑语言、时区… Sun 公司工程师开发了一简单获取对象的方式,直接使用即可,不要自己 new 创建对象获得
- Calendar 类定义了静态方法:
static Calendar getInstance()
返回的是 Calendar 的子类的对象GregorianCalendar
(GregorianCalendar
是方法中自带原有的 new 创建的对象,直接调用即可)
import java.util.Calendar;
public class CalendarTest {
public static void main(String[] args) {
getInstance();
}
/**
* 获取Calendar类的对象
* 使用静态方法获取
*/
public static void getInstance(){
Calendar calendar = Calendar.getInstance(); // 返回子类对象,体现多态性
System.out.println(calendar.toString()); // 获得日历字段
}
}
(2) 日历类的方法
① int get(int field)
返回给定日历字段的值
int get(int field)
返回给定日历字段的值- 日历中的任何数据,都是 int 类型
- 参数是具体的日历字段,传递年、月、日
- 日历字段的写法:参看 Calendar 类的静态成员变量(字段摘要中)
import java.util.Calendar;
public class CalendarTest {
public static void main(String[] args) {
calendarGet();
}
/**
* Calendar类的方法 get()
* 获取日历字段
*/
public static void calendarGet(){
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
System.out.println(year); // 获取当前的年份
System.out.println( calendar.get(Calendar.YEAR)+"年" + (calendar.get(Calendar.MONTH) +1)+"月" +
calendar.get(Calendar.DAY_OF_MONTH)+"日" + calendar.get(Calendar.HOUR_OF_DAY)+"点" +
calendar.get(Calendar.MINUTE)+"分"+calendar.get(Calendar.SECOND)+"秒");
}
}
优化写法:
import java.util.Calendar;
public class CalendarTest {
public static void main(String[] args) {
Calendar calendar=Calendar.getInstance();
calendarGet(calendar);
}
/**
* Calendar类的方法 get()
* 获取日历字段
*/
public static void calendarGet(Calendar calendar){
System.out.println( calendar.get(Calendar.YEAR)+"年" + (calendar.get(Calendar.MONTH) +1)+"月" +
calendar.get(Calendar.DAY_OF_MONTH)+"日" + calendar.get(Calendar.HOUR_OF_DAY)+"点" +
calendar.get(Calendar.MINUTE)+"分"+calendar.get(Calendar.SECOND)+"秒");
}
}
② void set()
修改日历的值
void set()
修改日历的值set(int field,int value)
field要修改的字段,value 具体的数据set(int,int,int)
传递年、月、日
import java.util.Calendar;
public class CalendarTest {
public static void main(String[] args) {
calendarSet();
}
/**
* Calendar 类的方法 set()
* 设置日历字段
*/
public static void calendarSet(){
Calendar calendar = Calendar.getInstance() ; // 操作系统时间
// 自己设置日历,传递年、月、日,可以设置多个值
calendar.set(2022,3,30); // 月份要做加一处理
// 调用 calendarGet,输出日历
calendarGet(calendar);
// 设置某一个字段,可以设置一个值
calendar.set(Calendar.DAY_OF_MONTH,15); // 即使设置的数值不对,它也会自动调整
// 调用calendarGet,输出日历
calendarGet(calendar);
}
/**
* Calendar类的方法get()
* 获取日历字段
*/
public static void calendarGet(Calendar calendar){
System.out.println( calendar.get(Calendar.YEAR)+"年" + (calendar.get(Calendar.MONTH) +1)+"月" +
calendar.get(Calendar.DAY_OF_MONTH)+"日" + calendar.get(Calendar.HOUR_OF_DAY)+"点" +
calendar.get(Calendar.MINUTE)+"分"+calendar.get(Calendar.SECOND)+"秒");
}
}
③ add()
设置日历字段的偏移量
add()
设置日历字段的偏移量add(int field,int value)
field 要修改的字段,value 具体的数据
import java.util.Calendar;
public class CalendarTest02 {
public static void main(String[] args) {
calendarAdd();
}
/**
* Calendar 类的方法 add()
* 设置日历字段的偏移量
*/
public static void calendarAdd(){
Calendar calendar = Calendar.getInstance() ; // 操作系统时间
// 日历向后,偏移180天
calendar.add(Calendar.DAY_OF_MONTH,180);
calendarGet(calendar);
}
/**
* Calendar 类的方法 get()
* 获取日历字段
*/
public static void calendarGet(Calendar calendar){
System.out.println( calendar.get(Calendar.YEAR)+"年" + (calendar.get(Calendar.MONTH) +1)+"月" +
calendar.get(Calendar.DAY_OF_MONTH)+"日" + calendar.get(Calendar.HOUR_OF_DAY)+"点" +
calendar.get(Calendar.MINUTE)+"分"+calendar.get(Calendar.SECOND)+"秒");
}
4. 日期格式化
自定义日期的格式:自己的喜好,定义日期的格式
(1) DateFormat 日期格式化
java.text.DateFormat 类:类的作用是格式化日期的,但是抽象类不能建立对象,需要创建子类的对象
SimpleDateFormat
(2) SimpleDateFormat 子类使用
- 构造方法:带有 String 参数的构造方法
- 参数字符串:日期格式化后的样子
- 调用 SimpleDateFormat 类的父类方法 format
String format(Date date)
传递日期对象,返回字符串
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatTest {
public static void main(String[] args) {
format();
}
/**
* 日期的格式化
*/
public static void format(){
// 严格区分大小写
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒");
String str = sdf.format(new Date());
System.out.println("str = " + str);
}
}
- 字符串转成日期对象:
- SimpleDateFormat 调用方法
Date parse(String str)
- SimpleDateFormat 调用方法
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatTest {
public static void main(String[] args) throws ParseException {
parse();
}
/**
* 日期的格式化
*/
public static void format(){
// 严格区分大小写
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒");
String str = sdf.format(new Date());
System.out.println("str = " + str);
}
/**
* 字符串转成日期对象
*/
public static void parse() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
/**
* dateString 用户输入的日期
* 转成 Date 对象
* 前提 : 格式必须和 SimpleDateFormat("格式一致")
*/
String dateString = "2021-04-13";
// sdf 对象的方法 parse
Date date = sdf.parse(dateString);
System.out.println("date = " + date);
}
}
(3) 时区
import java.util.TimeZone;
public class TimeZoneTest {
public static void main(String[] args) {
// TimeZone 静态方法 .getDefault() 默认的时区
TimeZone timeZone = TimeZone.getDefault();
System.out.println("timeZone = " + timeZone);
// 获取全球时区
String[] strings=TimeZone.getAvailableIDs();
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
}
四、 JDK8 新的时间日期对象
1. LocalDate 本地日期
(1) 获取该类的对象
- 获取该类的对象,属于静态方法
static LocalDate now()
获取 LocalDate 的对象,跟随操作系统static LocalDate of()
获取 LocalDate 的对象,可以自己设置日期- of 方法中传递年、月、日
of(int year,int month,int day)
- of 方法中传递年、月、日
import java.time.LocalDate;
public class LocalDateTest {
public static void main(String[] args) {
getInstance();
}
/**
* LocalDate 的静态方法获取对象
*/
public static void getInstance(){
// 静态方法 now()
LocalDate localDate = LocalDate.now();
System.out.println("localDate = " + localDate);
// 静态方法 of() 设置日期
LocalDate of = LocalDate.of(2022,5,10);
System.out.println("of = " + of);
}
}
(2) 获取日期字段的方法
- 获取日期字段的方法:名字是 get 开头,非静态方法
int getYear()
获取年份int getDayOfMonth()
返回月中的天数int getMonthValue()
返回月份
import java.time.LocalDate;
public class LocalDateTest {
public static void main(String[] args) {
get();
}
/**
* LocalDate 类的方法 getXXX() 获取日期字段
*/
public static void get(){
LocalDate localDate = LocalDate.now();
// 获取年份
int year = localDate.getYear();
// 获取月份
int monthValue = localDate.getMonthValue();
// 获取天数
int dayOfMonth = localDate.getDayOfMonth();
System.out.println("year = " + year);
System.out.println("monthValue = " + monthValue);
System.out.println("dayOfMonth = " + dayOfMonth);
}
}
(3) 设置日期字段的方法
- 设置日期字段的方法:名字是 with 开头
LocalDate withYear(int year)
设置年份LocalDate withMonth(int month)
设置月份LocalDate withDayOfMonth(int day)
设置月中的天数- LocalDate 对象是不可变对象,设置方法 with 开头,返回新的 LocalDate 对象
import java.time.LocalDate;
public class LocalDateTest {
public static void main(String[] args) {
with();
}
/**
* LocalDate类的方法 withXXX()设置日期字段
*/
public static void with(){
LocalDate localDate = LocalDate.now();
System.out.println("localDate = " + localDate);
// 设置年、月、日,不能返回原来的 LocalDate 对象,应为不可改变,要创建一个新的对象
// 方法调用链
LocalDate newLocal = localDate.withYear(2025).withMonth(10).withDayOfMonth(25);
System.out.println("newLocal = " + newLocal);
}
}
(4) 设置日期字段的偏移量
- 设置日期字段的偏移量,方法名 plus 开头,向后偏移
- 设置日期字段的偏移量,方法名 minus 开头,向前偏移
import java.time.LocalDate;
public class LocalDateTest {
public static void main(String[] args) {
minus();
plus();
}
/**
* LocalDate 类的方法 minusXXX() 设置日期字段的偏移量,向前偏移
*/
public static void minus() {
LocalDate localDate = LocalDate.now();
// 月份偏移10个月
LocalDate minusMonths = localDate.minusMonths(10);
System.out.println("minusMonths = " + minusMonths);
}
/**
* LocalDate 类的方法 plusXXX() 设置日期字段的偏移量,向后偏移
*/
public static void plus(){
LocalDate localDate = LocalDate.now();
// 月份偏移10个月
LocalDate plusMonths = localDate.plusMonths(10);
System.out.println("plusMonths = " + plusMonths);
}
}
2. Period 和 Duration 类
(1) Period 计算日期之间的偏差
static Period between(LocalDate d1,LocalDate d2)
计算两个日期之间的差值- 计算出两个日期相差的天数,月数,年数
import java.time.LocalDate;
import java.time.Period;
public class PeriodTest {
public static void main(String[] args) {
between();
}
public static void between(){
// 获取2个对象,LocalDate
LocalDate d1 = LocalDate.now();
LocalDate d2 = LocalDate.of(2022,6,1);
// Period 类的静态方法计算
Period period = Period.between(d1, d2); // 前面传小的日期,后面传大的日期
// period 类的非静态方法,获取计算的结果
int years = period.getYears();
System.out.println("相差的年:"+years);
int months = period.getMonths();
System.out.println("相差的月:"+months);
int days = period.getDays();
System.out.println("相差的天:"+days);
}
}
(2) Duration 计算时间之间的偏差
static Period between(Temporal d1,Temporal d2)
计算两个日期之间的差值(Temporal 是一个接口)
import java.time.Duration;
import java.time.LocalDateTime;
public class DurationTest {
public static void main(String[] args) {
between();
}
public static void between(){
LocalDateTime d1 = LocalDateTime.now();
LocalDateTime d2 = LocalDateTime.of(2022,6,1,11,32,20);
// Duration 静态方法进行计算对比
Duration duration = Duration.between(d1, d2);
// Duration 类的对象,获取计算的结果
long minutes = duration.toMinutes();
System.out.println("相差分钟:" + minutes);
long days = duration.toDays();
System.out.println("相差天数:"+days);
long millis = duration.toMillis();
System.out.println("相差秒:" + millis);
long hours = duration.toHours();
System.out.println("相差小时:"+hours);
}
}
(3) JDK8 的时区
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ZonedDateTest {
public static void main(String[] args) {
// JDK8 的时区
ZonedDateTime now01=ZonedDateTime.now();
System.out.println("now01 = " + now01);
ZonedDateTime now02=ZonedDateTime.now(ZoneId.of("America/New_York")); // 设置时区
System.out.println("now02 = " + now02);
}
}
3. DateTimeFormatter
JDK8 中的日期格式化对象:java.time.format 包
static DateTimeFormatter ofPattern(String str)
自定义的格式String format(TemporalAccessor t)
日期或者时间的格式化(其中的参数是一个接口)TemporalAccessor parse(String s)
字符串解析为日期对象
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
public class DateTimeFormatterTest {
public static void main(String[] args) {
format(); // 方法 format 格式化
parse(); // 方法 parse,字符串转日期
}
/**
* 方法 format 格式化
*/
public static void format(){
// 静态方法,传递日期格式,返回本类的对象
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// dateTimeFormatter 对象调用方法 format
String format = dateTimeFormatter.format(LocalDateTime.now());
System.out.println(format);
}
/**
* 方法 parse,字符串转日期
*/
public static void parse(){
// 静态方法,传递日期格式,返回本类的对象
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String str = "2021-04-13 15:55:55";
// dateTimeFormatter 调用方法 parse 转换
// 返回接口类型,接口是 LocalDate、LocalDateTime 都实现了该接口
TemporalAccessor temporalAccessor = dateTimeFormatter.parse(str);
System.out.println(temporalAccessor); // 打印的是 toString 字符串
LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
System.out.println(localDateTime);
}
}
五、 基本数据类型对象包装类
基本数据类型,一共有8种,可以进行计算,但是功能上依然不够用,JDK 提供了一套基本数据类型的包装类,功能增强,全部在 lang 包中
基本数据类型 | 对应的包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
基本数据类型的包装类的最重要功能:实现类基本数据类型和 String 的互转
1. 基本类型 int 变成 Integer 类的对象
- Integer 类的构造方法:
Integer(int a)
int 类型转成 Integer 对象Integer(String s)
字符串转成 Integer 对象,前提:字符串必须纯数字格式static Integer valueOf(int a)
int 类型转成 Integer 对象static Integer valueOf(String s)
字符串转成 Integer 对象,前提:字符串必须纯数字格式
这两套可以随意选择使用
/**
* 基础数据类型对象包装类:Integer
*/
public static void main(String[] args) {
getInstance();
}
/**
* 创建 Integer 类的对象
* 构造方法,new
* 使用 static 方法 valueOf
*/
public static void getInstance(){
Integer i1 = new Integer(100); // int 类型转成 Integer 对象
Integer i2 = new Integer("120"); // 字符串转成 Integer 对象
System.out.println(i1); // 这里调用方法 toString()
System.out.println(i2); // 这里调用方法 toString()
Integer i3 = Integer.valueOf(200); // int 类型转成 Integer 对象
Integer i4 = Integer.valueOf("220"); // 字符串转成 Integer 对象
System.out.println(i3);
System.out.println(i4);
}
2. String 对象转成基本数据类型 int
static int parseInt(String str)
参数字符串转成基本类型,字符串要求是数字格式(静态方法)int intValue()
把 Integer 对象构造方法中的字符串,转成基本类型(非静态方法)
/**
* 字符串转成基本类型 int
* 静态方法 parseInt()
* 非静态方法 intValue()
*/
public static void stringToInt(){
// 第一种方式:(推荐使用)
int i = Integer.parseInt("100"); // 字符串转成基本类型 int
System.out.println(i+1);
// 第二种方式:
Integer integer = new Integer("2");
int j = integer.intValue();
System.out.println(j+1);
}
3. 自动装箱和拆箱
- 自动装箱 : 基本数据类型 自动转成 引用类型 int → Integer
- 自动拆箱 : 引用类型 自动转成 基本数据类型 Integer → int
/**
* 自动装箱和拆箱
*/
public static void auto(){
// 自动装箱 int 类型自动转成 Integer 对象
// javac 编译特效,编译完成是 Integer integer = Integer.valueOf(1000) 本质还是 new Integer
Integer integer = 1000;
System.out.println(integer);
// 自动拆箱 Integer 类型自动转成 int 类型
// javac 编译特效, integer + 1; 编译完成是: integer.intValue() 返回 int 类型 之后加一等于 1001
// 又进行 Integer integer2 = 1001 装箱过程
Integer integer2 = integer + 1;
System.out.println(integer2);
// 全部都是自动进行的
}
自动装箱和拆箱中的问题:
/**
* 自动装箱和拆箱中的问题
*/
public static void auto(){
Integer i1 = 1000; // new Integer(1000)
Integer i2 = 1000; // new Integer(1000)
System.out.println("i1==i2:" + (i1 == i2) ); // 比较的是地址 false
System.out.println(i1.equals(i2)); // 比较的是值 true
Integer i3 = new Integer(1);
Integer i4 = new Integer(1);
System.out.println("i3==i4::"+(i3 == i4));// 比较的是地址 false
System.out.println(i3.equals(i4)); // 比较的是值 true
Integer i5 = 127; // 编译成 Integer.valueOf(127);
Integer i6 = 127;
System.out.println("i5==i6:"+(i5 == i6)); // true 但是数据不要超过 byte 超过就是 false
}
六、 异常
异常:程序在运行中出现的不正常现象就是异常
1. 异常继承体系
一切都是对象,异常也是对象,JDK 为异常定义了大量的类,类之间产生继承关系
异常中的顶级父类:
- java.lang.Throwable :所有异常和错误的父类
- java.lang.Error :所有错误的父类(java.lang.Throwable 的子类)
- java.lang.Exception :所有异常的父类(java.lang.Throwable 的子类)
- java.lang.RuntimeExeption :所有的运行异常父类(java.lang.Exception 的子类)
错误:程序中出现了错误,程序人员只能修改代码,否则不能运行
异常:程序中出现了异常,可以把异常处理掉,程序继续执行
2. Throwable 的方法
String toString()
返回异常信息的简短描述 (控制台红色部分)String getMessage()
返回异常信息的详细描述void printStackTrace()
异常信息追踪到标准的错误流
测试:
public static void main(String[] args) {
int[] arr = {1};
// try catch异常处理,将可能发生异常的代码写入 try catch 之中
try {
int i = getNum(arr);
System.out.println("i = " + i);
}catch (Exception ex){
// Throwable 类的,异常信息的处理方法
String message=ex.getMessage();
System.out.println("message = " + message); // message = 1 这里的 1 就是越界异常的下标
String str=ex.toString();
System.out.println("str = " + str); // str = java.lang.ArrayIndexOutOfBoundsException: 1
/**
* 控制台输出:出现问题的异常类的类,错误的原因,发生问题的的代码行数
* java.lang.ArrayIndexOutOfBoundsException: 1
* at com.xxxxxxx.object.ExceptionTest.getNum(ExceptionTest.java:23)
* at com.xxxxxxx.object.ExceptionTest.main(ExceptionTest.java:8)
*/
ex.printStackTrace();
}
// 加上 try...catch 之后其中的异常就会被处理,使得之后的语句可以继续执行
System.out.println("异常之后的的代码");
}
public static int getNum(int[] arr){
return arr[1] + 10;
}
子类继承即可使用
3. 异常的产生和默认的处理方式
故意引发异常:
public static void main(String[] args) {
int[] arr={1};
int i=getNum(arr);
System.out.println("i = " + i);
}
public static int getNum(int[] arr){
return arr[1]+10;
}
// arr[1] 索引不存在,JVM 检测到索引的问题,JVM 创建了一个对象
// new ArrayIndexOutOfBoundsException(1) 将索引 1 传入
// JVM 检测 getNum 方法中是否能处理掉这个异常,如果不能处理这个异常,就将异常对象抛出
// 抛出到 getNum 方法的调用者 main 方法
// main 方法收到了异常,也无法处理这个异常
// 异常对象就会继续抛出
// 抛出到 main 的调用者 JVM
// JVM 该异常不能处理,就会自己处理:输出信息,结束程序
- JVM 对多方都不能处理的异常进行了处理:输出信息,结束程序
- 如果可以处理异常,没有异常,继续执行程序