常用API与异常

常用API

String类

概述

String类在java.lang包下,所以使用的时候不需要导包

String类代表字符串,java程序中的所有字符串文字都被实现为此类的实例也就是说,java程序中所有的双引号字符串,都是String类的对象

字符串不可变,它们的值在创建后不能被更改

字符串的特点

  1. java程序中所有的双引号字符串,都是String类型的对象

  2. 字符串不可变,他们的值在创建后不能被改变

  3. 虽然String的值是不可变的,但是它们可以共享

注意

所有字符串常量都会存在方法区的字符串常量池中

使用字符串字面量创建对象时,系统会检查该字符串是否存在字符串常量池(方法区中)存在,如果不存在,会创建,如果存在,不会重新创建而是直接复用

创建字符串对象的区别对比

通过构造方法创建

通过new创建的字符串对象,每一次new都会申请一个内存空间,虽然内容相同,但是地址值不相同

直接赋值方式创建

以""方式给出的字符串,只要字符序列相同(顺序和大小写),无论在程序代码中出现几次,JVM都只会建立一个String对象,并在字符串池中维护

字符串的比较

==比较基本数据类型:比较的是具体的值

==比较引用数据类型:比较的是对象的地址值

String类:public boolean equals(String s) 比较两个字符串内容是否相同、区分大小写

equalsIgnoreCase:忽略大小写比较字符串内容

字符串面试常见题

打印字符串时直接会打印String类型的值,不会打印String对象的地址

如果在打印语句中,打印对象,自动调用对象的toString方法 toString方法就会打印字符串的内容

public class StringExam01 {
    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "abc";
        String str3 = new String("abc");
        System.out.println(str1);
        //为什么不是打印字符串的地址,而是打印字符串的内容
        //打印对象,自动调用对象的toString方法    toString方法就会打印字符串的内容
        System.out.println(str1 == str2);
        System.out.println(str1 == str3);
    }
}
​
运行结果:
abc
true
false    

注意:当字符串使用"+"号完成拼接时,系统底层会自动创建一个StringBuilder对象,然后调用append方法完成拼接,拼接后在调用toString转换为String类型对象

public class StringExam02 {
    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "ab";
        String str3 = str2+"c";
        //TODO 注意:当字符串使用"+"号完成拼接时,
        // 系统底层会自动创建一个StringBuilder对象,
        // 然后调用append方法完成拼接,拼接后在调用toString转换为String类型对象
        System.out.println(str1 == str3);
    }
}
​
​
运行结果:
    false

注意:java中存在常量优化机制,在编译时会将“a”+"b"+"c"拼接成“abc”。

示例

public class StringExam04 {
    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "a"+"b"+"c";
        System.out.println(str1 == str2);
    }
}

String类常用方法

public boolean equals(Object anObject) 比较字符串的内容,严格区分大小写

示例:

import java.util.Scanner;
​
public class StringExer01 {
    /*
     * 已知用户名和密码,请用程序实现模拟用户登录。总共三次机会,登录之后,给出相应的提示
     * */
    public static void main(String[] args) {
        /*
        * 1. 已知用户名和密码,定义两个字符串表示即可
        * 2. 键盘录入要登录的用户名和密码,用 Scanner 实现
        * 3. 拿键盘录入的用户名、密码和已知的用户名、密码进行比较,给出相应的提示。
        * 4. 字符串的内容比较,用equals() 方法实现
        * 5. 用循环实现多次机会,这里的次数明确,采用for循环实现,并在登录成功的时候,使用break结束循
        * */
        //1. 已知用户名和密码,定义两个字符串表示即可
        String realUsername = "admin";
        String realpassword = "123456";
        //2. 键盘录入要登录的用户名和密码,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        //3.用循环实现多次机会,这里的次数明确,采用for循环实现,并在登录成功的时候,使用break结束循
        for (int i = 0;; i++) {
            System.out.println("请输入用户名:");
            String username = sc.next();
            System.out.println("请输入密码:");
            String password = sc.next();
            //4. 字符串的内容比较,用equals() 方法实现
            //5. 拿键盘录入的用户名、密码和已知的用户名、密码进行比较,给出相应的提示。
            if (username.equals(realUsername) && password.equals(realpassword)) {
                System.out.println("恭喜,你登录成功!");
                break;
            }else {
                if (i == 2) {
                    System.out.println("今日登录机会已用完,请24小时后重试。");
                    break;
                }else {
                    System.out.println("你输入的用户名或密码有误,请重新输入");
                }
            }
        }
    }
}

public boolean equalsIgnoreCase(String anotherString) 比较字符串的内容,忽略大小写

public class StringEqualsIgnore {
    public static void main(String[] args) {
        String str1 = "ASDFGh";
        String str2 = "asdfGH";
        System.out.println(str1.equalsIgnoreCase(str2));
    }
}
​
运行结果:
    true

public int length() 返回此字符的长度

public char charAt(int index) 返回指定索引处的char值

import java.util.Scanner;
​
public class StringDemo {
    //键盘录入一个字符串,使用程序实现在控制台遍历该字符串
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String str = sc.next();
        //通过String类提供的length()方法获取字符串长度,并通过charAt()方法获取字符的索引值的内容
        for (int i = 0; i < str.length(); i++) {
            if (i == str.length()-1) {
                System.out.println(str.charAt(i));
            }else {
                System.out.print(str.charAt(i) + ",");
            }
        }
    }
}
运行结果:
    请输入一个字符串:
    asdfg
    a,s,d,f,g

public char[] toCharArray() 将字符串拆分为字符数组后返回

import java.util.Scanner;
​
public class StringExer02 {
    //键盘录入一个字符串,统计该字符串中大小写字母字符,小写字母子符,数字字符出现的次数(不考虑其他字符)
    public static void main(String[] args) {
        //1、键入一个字符串,用Scanner实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String s = sc.next();
        //2、定义三个变量,来统计每一种类型字符出现的次数,初始值0。
        int upperCaseCount = 0;
        int lowerCaseCount = 0;
        int numberCaseCount = 0;
        //3、将字符串拆分为字符数组,public cahr[] toCharArray():将当前字符串拆分为字符数组并返回
        char[] chars = s.toCharArray();
        //4、遍历字符数组,得到每一个字符
        for (int i = 0; i < chars.length; i++) { //length为属性,不是方法
            if(chars[i] >= 'A' && chars[i] <= 'Z'){
                upperCaseCount++;
            }else if(chars[i] >= 'a' && chars[i] <= 'z'){
                lowerCaseCount++;
            }else if(chars[i] >= '0' && chars[i] <= '9' ){
                numberCaseCount++;
            }
        }
        System.out.println("大写字符出现的次数:"+upperCaseCount+",小写字符出现的次数"+ numberCaseCount+",数字字符出现的次数"+lowerCaseCount);
​
    }
}

public String substring(int beginIndex,int endIndex)根据开始和结束索引进行截取,取得新的字符串(包括头,不包含尾)

public String substring(int beginIndex)从传入的索引处截取,截取到末尾,得到新的字符串

import java.util.Scanner;
​
public class StringExer03 {
    /*
    * 手机号屏蔽-字符串截取
    * 需求:以字符串的形式从键盘接受一个手机号,将中间四位号码屏蔽
    * */
    public static void main(String[] args) {
        //通过Scanner键入一个电话号码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的手机号:");
        String phoneNum = sc.next();
        //截取手机号前三位 通过substring(int indexbegin,int indexend)方法进行截取
        String phoneBeginThree = phoneNum.substring(0, 3);
        System.out.print(phoneBeginThree);
        System.out.print("****");
        //截取手机号后四位 通过substring(int indexbegin)方法进行截取
        String phoneEndFour = phoneNum.substring(7);
        System.out.println(phoneEndFour);
    }
}

public String replace(CharSequence target,CharSequence replacement)使用新值,将字符串中的旧值替换,得到新的字符串

import java.util.Scanner;
​
public class StringExer04 {
    /*
    * 键盘录入一个 字符串,如果字符串中包含(TMD),则使用***替换
    * */
    public static void main(String[] args) {
        //1. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String line = sc.nextLine();
       /* 2. 替换敏感词
        String replace(CharSequence target, CharSequence replacement)
        将当前字符串中的target内容,使用replacement进行替换,返回新的字符串*/
        String newline = line.replace("TMD","***");//replace方法并不会改变原字符的内容
        //3. 输出结果
        System.out.println(newline);
    }
}

public String[] split(String regex)根据传入的规则切割字符串,得到字符串数组

package com.Exer.String类.test.bean;
​
public class Student {
    private String name;
    private int age;
​
    public Student(){}
​
    public Student(String name,int age){
        this.name = name;
        this.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;
    }
    public void show(){
        System.out.println("name = " + name +", age = " + age);
    }
}
import com.Exer.String类.test.bean.Student;
​
import java.util.Scanner;
​
public class StringExer05 {
    /*
    * 以字符串的形式从键盘录入学生信息,例如:“张三 , 23”
   从该字符串中切割出有效数据,封装为Student学生对象
    * */
    public static void main(String[] args) {
        //1. 编写Student类,用于封装数据
        //2. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串,格式(张三,23):");
        String line = sc.nextLine();
        /*3. 根据逗号切割字符串,得到(张三)(23)
        String[] split(String regex) :根据传入的字符串作为规则进行切割
        将切割后的内容存入字符串数组中,并将字符串数组返回*/
        String[] split = line.split(",");
        //4. 从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
        /*for (int i = 0; i < splite.length; i++) {
            System.out.println(split[i]);
        }*/
        String name = split[0];
        String ageStr = split[1];
        //通过Integer.parseInt()将String类型转换为int类型
        int age = Integer.parseInt(ageStr);
        Student student = new Student(name, age);
        //5. 调用对象getXxx方法,取出数据并打印。
        System.out.println(student.getName());
        System.out.println(student.getAge());
        student.show();
    }
}

StringBuilder类

StringBuilder是一个可变的字符串类,可以将它看作一个容器,这里的可变指的是StringBulider对象中的内容可变

常见的构造方法

public StringBuilder(){} 创建一个空白可变字符串对象,不含有任何内容

public StringBuulder(String str)

示例:

public class StringBuilderExer01 {
    public static void main(String[] args) {
        //public StringBuilder()创建一个空白可变字符串对象,不含有任何内容
        StringBuilder sb1 = new StringBuilder();
        System.out.println(sb1);//默认调用对象的toString方法,打印对象的内容
        System.out.println(sb1.length());
        System.out.println("===================================");
        //public StringBuilder(String str)
        StringBuilder sb2 = new StringBuilder("abc");
        System.out.println(sb2);
        System.out.println(sb2.length());
​
    }
}
StringBuilder常用的成员方法

添加和反转方法

public StringBulider append(任意类型) 添加数据,并返回对象本身

public StringBulider reverse() 返回相反的字符序列

示例:

public class StringBuilderExer02 {
​
    public static void main(String[] args) {
        //public StringBulider append(任意类型)    添加数据,并返回对象本身
        StringBuilder sb1 = new StringBuilder("abc");
        StringBuilder sb2 = sb1.append("abc");
        System.out.println(sb1);
        System.out.println(sb2);
        System.out.println(sb1 == sb2);
​
        //链式调用 每次调用返回的数据类型都是自己
        StringBuilder sb3 = sb1.append("abc").append("efg").append("hij").append(false);
        System.out.println(sb3);
        System.out.println(sb1);
        System.out.println(sb2);
​
        //public StringBulider reverse()   返回相反的字符序列
        StringBuilder reverse = sb1.reverse();
        System.out.println(reverse);
    }
}
​
​
运行结果:
    abcabc
    abcabc
    true
    abcabcabcefghijfalse
    abcabcabcefghijfalse
    abcabcabcefghijfalse
    eslafjihgfecbacbacba 
StringBuilder和String相互转换

StringBuilder转换为String

public String toString():通过toString()就可以实现把StringBuilder转换为String

String转换为StringBuilder

public StringBuulder(String str):通过构造方法就可以实现把String转换为StringBuilder

public class StringBuilderDemo03 {
    /*
    StringBuilder转换为String
​
    public String toString():通过toString()就可以实现把StringBuilder转换为String
​
    String转换为StringBuilder
​
    public StringBuulder(String str):通过构造方法就可以实现把String转换为StringBuilder
    */
​
    public static void main(String[] args) {
        String str = "hello";
        //通过构造方法转换为StringBuilder类型
        StringBuilder sb = new StringBuilder(str);
        System.out.println(sb);
        sb.append(" world");
        String result = sb.toString();
        System.out.println(result);
    }
}

Math类

概述

Math包含用于执行基本数据运算的方法

Math中的方法调用方法

Math类中无构造方法,但内部的方法都是静态的,则可以通过类名.进行调用

Math类中常用的方法

public static int abs(int a) 返回参数的绝对值

public static double ceil(doouble a) 返回大于或等于参数的最小double值,等于一个整数

public static double floor(double a) 返回或等于参数的最大double值,等于一个整数

public static int round(float a) 按照四舍五入返回最接近参数的int

public static int max(int a,int b) 返回两个int值的较大值

public static int min(int a,int b) 返回两个int值的较小值

public static double pow(double a,double b) 返回a的b次幂的值

public static double random() 返回值为double的正值,[0.0,1.0)

示例

public class Demo01 {
    public static void main(String[] args) {
        //public static int abs(int a)    返回参数的绝对值
        System.out.println(Math.abs(-10));
        //public static double ceil(doouble a)    返回大于或等于参数的最小double值,等于一个整数 向上取整
        System.out.println("=========================");
        System.out.println(Math.ceil(10.2));
        System.out.println(Math.ceil(10.5));
        System.out.println(Math.ceil(10.8));
        //public static double floor(double a)    返回或等于参数的最大double值,等于一个整数 向下取整
        System.out.println("=========================");
        System.out.println(Math.floor(10.7));
        System.out.println(Math.floor(10.5));
        System.out.println(Math.floor(10.3));
        //public static int round(float a)    按照四舍五入返回最接近参数的int
        System.out.println("=========================");
        System.out.println(Math.round(10.8));
        System.out.println(Math.round(10.5));
        System.out.println(Math.round(10.4));
        //public static int max(int a,int b)      返回两个int值的较大值
        System.out.println();
        System.out.println(Math.max(10,11));
        //public static int min(int a,int b)      返回两个int值的较小值
        System.out.println();
        System.out.println(Math.min(10,11));
        //public static double pow(double a,double b)     返回a的b次幂的值
        System.out.println(Math.pow(2,4));
        System.out.println(Math.pow(2,5));
        System.out.println(Math.pow(2,6));
        System.out.println(Math.pow(2,7));
        System.out.println(Math.pow(2,8));
        System.out.println(Math.pow(2,9));
        System.out.println(Math.pow(2,10));
        //public static double random()       返回值为double的正值,[0.0,1.0)
        //生成10-30之间的整数:0-20
        System.out.println(Math.random()*20+10);
    }
}
Math.random()与java.util.Random的用法不同
public class RandomAndMathRandom {
    public static void main(String[] args) {
        Random random = new Random();
        //[0,10)
        System.out.println(random.nextInt(10));
        System.out.println(Math.random()*10); //返回的是double类型的数
        //[10,20)
        System.out.println(random.nextInt(10)+10);
        System.out.println(Math.random()*10+10);

    }
}

System类

被final修饰,不能被继承。它也不能被实例化,没有提供构造方法,直接通过类名.进行调用

System类的常用方法

public static void exit(int status) 终止当前运行的java虚拟机,非零表示异常终止

public static long currentTimeMillis() 返回当前时间(以毫秒为单位)

public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) 从指定数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束

public class Demo01 {
    public static void main(String[] args) {
        //public static void exit(int status)     终止当前运行的java虚拟机,非零表示异常终止
        System.out.println("程序结束之前执行程序");
        int i = 0;
        while (true){
            System.out.println(Math.pow(2,i));
            i = i + 1;
            if (i == 10) {
                System.exit(0);
            }
        }
        //public static long currentTimeMillis()      返回当前时间(以毫秒为单位)
        System.out.println(System.currentTimeMillis()); //通常用于计算程序执行多少毫秒
        //public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)      从指定数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束
        /*
        Object src 原数组
        int srcPos 原数组的指定开始复制的位置
        Object dest 目标数组
        int destPos 指定复制目标数组的位置
        int length 指定长度90
        */
        int[] src = {23,12,34,53,53,45,20};
        int[] dest = new int[20];
        System.out.println("复制之前的目标数组dest:");
        for (int i = 0; i < dest.length; i++) {
            System.out.print(dest[i] + " ");
        }
        System.out.println();
        System.arraycopy(src,0,dest,2,7);
        System.out.println("复制之后的目标数组dest:");
        for (int i = 0; i < dest.length; i++) {
            System.out.print(dest[i] + " ");
        }
        System.out.println();
    }
}

Object类

public class Student {
    private String name;
    private int age;
​
    public Student() {
    }
​
    public Student(String name, int age) {
        this.name = name;
        this.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;
    }
​
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
​
        Student student = (Student) o;
​
        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }
​
    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
​
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

toString方法:无论是哪个对象进行输入出打印,都是会默认调用toString方法进行打印,但如果子对象中没有创建toString方法,则会去寻找父类Object中的toString方法,打印规则为getClass().getName() + "@" + Integer.toHexString(hashCode());

equals方法:在Object中的equals方法只是对地址进行==的逻辑

public class Demo02 {
    public static void main(String[] args) {
        Student stu1 = new Student("猪八戒", 19);
        System.out.println(stu1);
        Student stu2 = new Student("猪八戒", 19);
        System.out.println(stu2);
​
        //比较两个对象是否相等
        System.out.println(stu1.equals(stu2));
        //通过调用equals方法比较两个对象,但是对象所对应的类中没有equals,所以就去父类中找equals方法,而父类中equals比较的逻辑就是用==
        //如果不想通过父类的equals逻辑来进行比较,可以使用子类重写equals方法来重写比较逻辑 通常Alt+Insert 重写equals方法
    }
}

Objects类(1.7以后)

常用方法

public static String toString(对象) 返回参数中对象的字符串表示形式

public static String toString(对象,默认字符串) 返回对象的字符串表达形式

public static Boolean isNull(对象) 判断对象是否为空

public static Boolean nonNull(对象) 判断对象是否不为空

public class ObjectsDemo {
    /*
    public static String toString(对象)     返回参数中对象的字符串表示形式
​
    public static String toString(对象,默认字符串)       返回对象的字符串表达形式
​
    public static Boolean isNull(对象)      判断对象是否为空
​
    public static Boolean nonNull(对象)     判断对象是否不为空
    * */
    public static void main(String[] args) {
        //public static String toString(对象)       返回参数中对象的字符串表示形式
        Student stu = new Student("猪八戒", 20);
        System.out.println(Objects.toString(stu));
        //Objects.toString()实际就是调用stu对象的toString方法
​
        //public static String toString(对象,默认字符串)     返回对象的字符串表达形式
        //stu = null;
        System.out.println(Objects.toString(stu,"该对象为空"));
​
        //public static Boolean isNull(对象)    判断对象是否为空
        System.out.println(Objects.isNull(stu));
​
        //public static Boolean nonNull(对象)       判断对象是否不为空
        System.out.println(Objects.nonNull(stu));
    }
}

运行结果:
    执行了
    Student{name='猪八戒', age=20}
    执行了
    Student{name='猪八戒', age=20}
    false
    true
 

BigDecimal

运用场景(作用):

可以用来进行精确计算,适用于对精度比较高的场景,尤其用于金融场景下的金额的计算

构造方法

BigDecimal(String val) 将BigDecimal的字符串表示 BigDecimal转换为BigDecimal 。

BigDecimal(int val) 将int成BigDecimal 。

比较两种构造方法 通过传递字符串的构造方法才可以解决精度问题

import java.math.BigDecimal;
​
public class Demo1 {
    public static void main(String[] args) {
        double num1 = 0.1;
        String num2 = "0.1";
        //BigDecimal(String val)       将BigDecimal的字符串表示 BigDecimal转换为BigDecimal 。
        BigDecimal bd1 = new BigDecimal(num1);
        System.out.println(bd1);
        //BigDecimal(int val)      将int成BigDecimal 。
        BigDecimal bd2 = new BigDecimal(num2);
        System.out.println(bd2);
        
        //比较两种构造方法  通过传递字符串的构造方法才可以解决精度问题
    }
}
常用的方法

public BigDecimal add(另外一个BigDecimal对象) 加法

public BigDecimal subtract(另外一个BigDecimal对象) 减法

public BigDecimal multiply(另外一个BigDecimal对象) 乘法

public BigDecimal divide(另外一个BigDecimal对象) 除法

public BigDecimal divide(另外一个BigDecimal对象,精确几位,舍入模式) 除法

import java.math.BigDecimal;
​
public class Demo2 {
    public static void main(String[] args) {
        BigDecimal b1 = new BigDecimal("0.1");
        BigDecimal b2 = new BigDecimal("0.2");
        BigDecimal b3 = new BigDecimal("0.3");
        //public BigDecimal add(另外一个BigDecimal对象)     加法
        BigDecimal add = b1.add(b2);
        System.out.println("加法:"+add);
        //public BigDecimal subtract(另外一个BigDecimal对象)    减法
        BigDecimal substract = b2.subtract(b1);
        System.out.println("减法:"+substract);
        //public BigDecimal multiply(另外一个BigDecimal对象)    乘法
        BigDecimal multiply = b1.multiply(b2);
        System.out.println("乘法:"+multiply);
        //public BigDecimal divide(另外一个BigDecimal对象)      除法
        BigDecimal divide = b1.divide(b2);
        System.out.println("除法(没有循环,不需要取舍):"+divide);
        //public BigDecimal divide(另外一个BigDecimal对象,精确几位,舍入模式)    除法
        BigDecimal otherDivide  = b1.divide(b3,2,BigDecimal.ROUND_UP);//进一法
        BigDecimal otherDivide1  = b1.divide(b3,2,BigDecimal.ROUND_FLOOR);//去尾法
        BigDecimal otherDivide2  = b1.divide(b3,2,BigDecimal.ROUND_HALF_UP);//四舍五入
        System.out.println("除法(需要取舍)----进一法:"+otherDivide);
        System.out.println("除法(需要取舍)----去尾法:"+otherDivide1);
        System.out.println("除法(需要取舍)----四舍五入:"+otherDivide2);
​
    }
}
​
运行结果:
    加法:0.3
    减法:0.1
    乘法:0.02
    除法(没有循环,不需要取舍):0.5
    除法(需要取舍)----进一法:0.34
    除法(需要取舍)----去尾法:0.33
    除法(需要取舍)----四舍五入:0.33

包装类

基本数据类型包装类

作用

将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据

常用的操作之一:用于基本数据类型与字符串之间的转换

基本数据类型对应的包装类
基本数据类型包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

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) 返回一个保存指定值的Integer对象String

public class Demo1 {
    public static void main(String[] args) {
        //public Integer(int value)
        Integer integer1 = new Integer(10);
        //public Integer(String s)
        Integer integer2 = new Integer("10");
        System.out.println(integer1);
        System.out.println(integer2);
        //public static Integer valueOf(int i)    返回表示指定的int值的Integer实例
        Integer integer3 = Integer.valueOf(100);
        //public static Integer valueOf(String s)     返回一个保存指定值的Integer对象String
        Integer integer4 = Integer.valueOf("100");
        System.out.println(integer3);
        System.out.println(integer4);
    }
}
运行结果:
    10
    10
    100
    100
自动拆箱和自动装箱
public class Demo2 {
    public static void main(String[] args) {
        //基本数据类型--->引用数据类型  装箱操作
        //引用数据类型--->基本数据类型  拆箱操作
​
        //jdk1.5以后 自动装箱操作
        Integer i = 100;//整型字面量默认的类型int
​
        //jdk1.5以后 自动拆箱操作
        int a = i;//引用数据类型转换为基本数据类型
​
        Integer b = 200;
        b += 100; //b = b+100
        //b -> 基本数据类型 自动拆箱
        //参与基本数据类型运算 结果int基本数据类型
        //基本数据类型 -> 引用数据类型 自动装箱
        System.out.println(b);
    }
}
int和String类型的相互转换

int转换为String

方式一:直接在数字后面加一个空字符串

方式二:通过String类静态方法valueOf()

String转换为int

方式一:先将字符串数字转成Integer,自动拆箱

方式二:通过Integer静态方法parseInt()进行转换

public class Demo3 {
    public static void main(String[] args) {
        //**int转换为String**
        int i = 10;
        //    方式一:直接在数字后面加一个空字符串
        String s = 10 + "";
        System.out.println(s);
        //    方式二:通过String类静态方法valueOf()
        String s1 = String.valueOf(i);
        System.out.println(s1);
        System.out.println("----------------------");
​
​
        //**String转换为int**
        String str = "1234";
        //    方式一:先将字符串数字转成integer,自动拆箱
        int num = Integer.valueOf(str);
        System.out.println(num);
        //    方式二:通过Integer静态方法parseInt()进行转换
        int num1 = Integer.parseInt(str);
        System.out.println(num1);
    }
}

日期时间类

Date类

中国标准时间:世界标准时间+8小时

时间换算单位 1秒 = 1000毫秒

Date代表一个特定的时间,精确到毫秒

Date构造方法

Date() 分配一个 Date对象,并初始化它,以便它代表它被分配的时间,测量到最近的毫秒。

Date(long date) 分配一个Date对象,并将其初始化为表示自称为“时代”的标准基准时间以后的指定毫秒数,即1970年1月1日00:00:00 GMT。

import java.util.Date;
​
public class DateDemo {
    public static void main(String[] args) {
        //Date()      分配一个 Date对象,并初始化它,以便它代表它被分配的时间,测量到最近的毫秒。
        Date date = new Date();
        //这个时间表示当前系统时间
        System.out.println(date);
​
​
        //Date(long date) 分配一个Date对象,并将其初始化为表示自称为“时代”的标准基准时间以后的指定毫秒数,即1970年1月1日00:00:00  GMT。
        Date date1 = new Date(0L);
        //这个时间距离计算机原点时间多少ms的那个时间
        System.out.println(date1);
    }
}
Date类常用方法

public long getTime() 获取的是日期对象从1970年1月1日00:00:00到现在的毫秒值

public void setTime(long time) 设置时间,给的是毫秒值

import java.util.Date;
​
public class DateDemo1 {
    public static void main(String[] args) {
        //public long getTime()       获取的是日期对象从1970年1月1日00:00:00到现在的毫秒值
        Date date = new Date();
        //1970年1月1日00:00:00到现在的毫秒值
        System.out.println(date.getTime());
        System.out.println(System.currentTimeMillis());
​
​
        //public void setTime(long time)      设置时间,给的是毫秒值
        date.setTime(date.getTime());
        System.out.println(date);
    }
}
SimpleDateFormat类

SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期。

格式化 时间对象------> 时间字符串

解析 时间字符串------>时间对象

SimpleDateFormat类构造方法

public SimpleDateFormat() 构造一个SimpleDateFormat,使用默认模式和日期模式

public SimpleDateFormat(String pattern) 构造一个SimpleDateFormat使用给定的模式和默认的日期格式

SimpleDateFormat类的常用方法

格式化(从Date到String)

public final String format(Date date):将日期格式化成日期/时间字符串

解析(从String到Date)

public Date parse(String source):从给定的字符串的开始解析文本以生成日期

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
​
public class SimpleDateFormatDemo1 {
    public static void main(String[] args) throws ParseException {
        //创建时间对象
        Date date = new Date();
        //创建SimpleDateFormat
        //构造一个SimpleDateFormat,使用默认模式和日期格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        System.out.println(date);
        String format = simpleDateFormat.format(date);
        System.out.println(format);
​
        //构造一个SimpleDateFormat(String pattern)给定的模式和默认的日期格式
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = simpleDateFormat1.format(date);
        System.out.println(format1);
        //给定的时间字符串要跟SimpleDateFormat指定的时间格式的模式保持一致,如果不一致就会出现错误 ParseException Unparseable date
        //Date parse(String source):从给定字符串的开始解析文本以生成日期
        Date parse = simpleDateFormat1.parse(format1);
        System.out.println("解析后的时间对象:"+parse);
​
    }
}

JDK8时间日期类

JDK8新增日期类

LocalDate 表示日期(年月日)

LocalTime 表示时间(时分秒)

LocalDateTime 表示时间+日期(年月日时分秒)

LocalDateTime创建方法

public static LocalDateTime now() 获取当前系统时间

public static LocalDateTime of(年,月,日,时,分,秒) 使用指定年月日和时分秒初始化一个LocalDateTime对象

import java.time.LocalDateTime;
​
public class Jdk8DateLocalDemo1 {
    public static void main(String[] args) {
        //创建LocalDateTime对象
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
​
        //指定时间的对象
        LocalDateTime of = LocalDateTime.of(2025, 2, 15, 10, 10, 20);
        System.out.println(of);
    }
}

LocalDateTime获取方法

public int getYear() 获取年

public int getMonthValue() 获取月份(1-12月)

public int getDayOfMonth() 获取月份中的第几天(1-31)

public int getDayOfYear() 获取一年中的第几天(1-366)

public DayOfWeek getDayOfWeek 获取星期

public int getMinute 获取分钟

public int getHour() 获取小时

import java.time.LocalDateTime;
​
public class LocalDateTimeDemo1 {
    public static void main(String[] args) {
        //LocalDateTime获取方法
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //public int getYear()    获取年
        System.out.println(now.getYear());
        //public int getMonthValue()      获取月份(1-12月)
        int monthValue = now.getMonthValue();
        System.out.println(monthValue);
        //public int getDayOfMonth()      获取月份中的第几天(1-31)
        System.out.println(now.getDayOfMonth());
        //public int getDayOfYear()       获取一年中的第几天(1-366)
        System.out.println(now.getDayOfYear());
        //public DayOfWeek getDayOfWeek       获取星期
        System.out.println(now.getDayOfWeek());
        //public int getMinute    获取分钟
        System.out.println(now.getMinute());
        //public int getHour()    获取小时
        System.out.println(now.getHour());
    }
}
LocalDateTime转换方法

public LocalDate toLocalDate() 转换成为一个LocalDate对象

public LocalTime toLocalTime() 转换成为一个LocalTime对象

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
​
public class LocalDateTimeDemo2 {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        //public LocalDate toLocalDate()      转换成为一个LocalDate对象
        LocalDate localDate = now.toLocalDate();
        System.out.println(localDate);
        //public LocalTime toLocalTime()      转换成为一个LocalTime对象
        LocalTime localTime = now.toLocalTime();
        System.out.println(localTime);
    }
}
LocalDateTime格式化和解析
方法说明

public String format(指定格式) 把一个LocalDateTime格式化成为一个字符串

public LocalDateTime parse(准备解析的字符串,解析格式) 把一个日期字符串解析成为一个LocalDateTime对象

public static DateTimeFormatter ofPattern(String pattern) 使用指定的日期模板获取一个日期格式化器DateTimeFormatter对象

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
​
public class LocalDateTimeDemo3 {
    public static void main(String[] args) {
        //格式化
        method1();
        //解析
        method2();
    }
    public static void method1(){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = now.format(formatter);
        System.out.println(format);
    }
    public static void method2(){
        String strDate = "2024-06-26 09:10:20";
​
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
​
        LocalDateTime parse = LocalDateTime.parse(strDate, formatter);
        System.out.println(parse  );
    }
}

异常

异常体系

Error:严重问题,通过代码无法处理

比如:内存溢出

Exception(异常类):它表示程序本身可以处理的问题

RuntimeException及其子类:运行时异常。(空指针异常,数组索引越界异常)

除RuntimeException之外所有的异常:编译期必须处理的,否则程序不能通过编译(日期格式化异常)

编译异常和运行异常的区别

简单来说:编译时异常就是在编译的时候出现异常,运行时异常就是在运行时出现的异常。

编译时异常

都是Exception类及其子类

必须显示处理,否则程序就会发生错误,无法通过编译

运行时异常

都是RuntimeException类及其子类

无需显示处理,也可以和编译时异常一样处理

当程序出现异常时

1、会在异常的位置生成一个异常类的对象

2、看程序是否有自己处理异常的代码 java中异常处理的两种方式:throws try-catch

3、如果有,则按照处理异常的逻辑处理,如果没有,它会交给方法的调用者来处理

4、方法调用会依次传递给main方法,如果main依然没有处理,就抛给jvm来处理(把异常的名称,错误原因及异常出现的位置等信息输出在了控制台,终止程序运行)

throws声明异常

定义格式

public void 方法() throws 异常类名{
    
}

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
​
public class ExceptionDemo1 {
    //告诉方jvm,该方法可能会出现异常ParseException
    public static void main(String[] args) throws NullPointerException {
        method1();
        method2();
        System.out.println("程序执行结束");
    }
    //告诉方法的调用者,该方法可能会出现异常NullPointerException
    //运行时异常(可以省略throws声明)
    public static void method1() throws NullPointerException{
        String str = null;
        System.out.println(str.toUpperCase());//NullPointerException 空指针异常
        System.out.println("方法执行结束");
    }
    //告诉方法的调用者,该方法可能会出现异常ParseException
    //编译时异常(不可以省略throws声明)
    public static  void method2() throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        simpleDateFormat.parse(format);//ParseException 解析异常
    }
}

注意事项

这个throws格式是跟在方法的括号后面的

运行时异常因为在运行时才发生,所以在方法后面可以不写,运行时出现异常默认交给jvm处理

编译时异常必须要进行处理,两种处理方案:try...catch...或者throws,如果采用throws这种方案,在方法上进行显示声明,将来谁调用这个方法谁处理

throw抛出异常

格式:

throw new 异常()

注意

这个格式是在方法内的,表示当前代码手动抛出一个异常,下面的代码不用在执行了

throws和throw的区别

throwsthrow
用在方法名后面,跟的时异常类名用在方法体内,跟的是异常对象名
表示声明异常,调用该方法有可能会出现这样的异常表示手动抛出异常对象,由方法体内的语句处理

try-catch方法处理异常

定义格式

try{
    可能出现异常的代码;
}catch(异常类名 变量名){
    异常的处理代码;
}

执行流程

程序从try里面的代码开始执行

出现异常,就会跳转到对应的catch里面去执行

执行完毕之后,程序还可以继续往下执行

public class ExceptionDemo4 {
    public static void main(String[] args) throws Exception{
        int[] arr = {1,2,3,4,5};
        arr = null;
        //处理 真正处理异常
        try{
            printArr(arr);
        }catch (Exception e){
            System.out.println("数组参数不能为空");
        }
​
        
        System.out.println("程序执行结束");
    }
​
    private static void printArr(int[] arr) throws Exception {
        //方法中可以对参数做校验,校验结果可以通过异常来抛出
        if (arr == null) {
            throw new Exception();
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

finally关键字

finally 关键字用来创建在 try 代码块后面执行的代码块。

无论是否发生异常,finally 代码块中的代码总会被执行。

在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。

finally 代码块出现在 catch 代码块最后,语法如下:

try{  
// 程序代码 
}catch(异常类型1 异常的变量名1){  
// 程序代码 
}catch(异常类型2 异常的变量名2){  
    // 程序代码 
}finally{  
    // 程序代码 }

注意

1、如果try中没有遇到问题,怎么执行?

会把try中所有的代码全部执行完毕,不会执行catch里面的代码

2、如果try遇到了问题,那么try下面的代码还会执行吗?

那么直接跳转到对应的catch语句中,try下面的代码就不会在执行了

当catch里面的语句全部执行完毕,表示整个体系全部执行完全,继续执行下面的代码

3、如果出现的问题没有被捕获,那么程序如何运行?

那么try...catch就相当于没有写,那么也就是自己没有处理

默认交给jvm处理

4、同时有可能出现多个异常怎么处理? 出现多个异常,那么就写多个catch就可以了。

注意点:如果多个异常之间存在子父类关系,那么父类一定要写在下面

import java.util.InputMismatchException;
import java.util.Scanner;
​
public class ExceptionDemo5 {
    public static void main(String[] args) throws Exception{
        //如果try中没有遇到问题,怎么执行?会把try中所有的代码全部执行完毕,不会执行catch里面的代码
        //如果try遇到了问题,那么try下面的代码还会执行吗?那么直接跳转到对应catch语句中,try下面的代码就不会在执行了,当catch里面的语句全部执行完毕,表示整个体系全部执行完全,继续执行下面的代码
        //如果出现的问题没有被捕获,那么程序如何运行?那么try...catch就相当于没有写。那么也就时自己没有处理,默认交给虚拟机处理
        //同时有可能出现多个异常怎么处理?出现多个异常,那么就写多个catch就可以了。注意点:如果多个异常之间存在子父类关系,那么父类一定写在下面
​
        //ctr+alt+t  选择try...catch
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个整数:");
            int num = sc.nextInt();
            System.out.println(num);
            System.out.println(10/0);
        } catch (InputMismatchException inputMismatchException) {
            System.out.println("你输入的不是一个整数");
        }catch (ArithmeticException arithmeticException){
            System.out.println("分母不能为0");
        }catch (Exception e){
            System.out.println("出现异常了");
        }
        System.out.println("程序执行结束");
    }
}

两种处理方式总结

"抛"模型:throw / throws

在方法中,当传递的参数有误,没有继续执行下去的意义时,则采用抛出异常处理方法

抛出异常相当于告诉调用者程序可能会抛出异常

throws声明抛出的异常如果是运行时异常可以省略,如果是编译时异常必须动手声明

抛出异常后的代码不会执行

"抓"模型:try-catch

真正处理异常,异常处理后代码可以继续往下执行

Throwable成员方法

常用方法

public String getMessage() 返回此throwable的详细消息字符串

public String toString() 返回此可抛出的简短描述

public void printStackTrace() 把异常的错误信息输出到控制台

public class ExceptionDemo6 {
    public static void main(String[] args){
        try {
            int[] arr = new int[]{1,2,3,4,5};
            System.out.println(arr[5]);//在try中程序出现了异常,自动生成一个异常对象 new ArrayIndexOutOfBoundsException()
        } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) {
            //public String getMessage()      返回此throwable的详细消息字符串
            String message = arrayIndexOutOfBoundsException.getMessage();
            System.out.println(message);
            //public String toString()    返回此可抛出的简短描述
            String string = arrayIndexOutOfBoundsException.toString();
            System.out.println(string);
            //public void printStackTrace()       把异常的错误信息输出到控制台
            arrayIndexOutOfBoundsException.printStackTrace();
        }
        System.out.println("程序执行结束");
    }
}
运行结果
5
java.lang.ArrayIndexOutOfBoundsException: 5
程序执行结束
java.lang.ArrayIndexOutOfBoundsException: 5
    at com.Exer.commonapi.exception.ExceptionDemo6.main(ExceptionDemo6.java:8)

自定义异常

在java中提供的异常不能满足我们的需求时,我们可以自定义异常

实现步骤:

1、定义异常

2、写继承关系

3、提供空参构造

4、提供带参构造

public class AgeOutOfBandsException extends RuntimeException{
    /*
    * 定义异常
    * 写继承关系
    * 提供空参构造
    * 提供带参构造
    * */
    /*
    * 自定义异常:学生年龄超出异常
    * */
    public AgeOutOfBandsException(){super();}
​
    public AgeOutOfBandsException(String s){super(s);}
}

  • 27
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值