【Java常用API】

`-```day03 【常用API】

今日内容

  • 权限修饰符
    • 分类
    • 权限
  • 代码块(格式,位置,执行,使用场景)
    • 构造代码块
    • 静态代码块
    • 局部代码块
  • Object类
  • 时间日期类
  • Math类(静态方法)
  • System类(静态方法)
  • BigInteger类
  • BigDecimal类
  • Arrays类
  • 包装类

第一章 权限修饰符

1.1 权限修饰符

概述
  • 在java中提供了4个权限修饰符,使用不同的权限修饰符修饰,被修饰的内容就具有不同的访问权限
  • 分类:
    • public : 公共的
    • protected: 受保护的
    • (空的): 默认
    • private: 私有的
不同权限的访问能力
			同一个类		同一个包		不同包的父子类			不同包的无关类
public   	√				√				√					√
protected	√				√				√					×
默认		   √			   √               ×                   ×
private     √               ×               ×                   ×
  • 案例:

    同一个包:
    package com.itheima.demo1_权限修饰符;
    
    /**
     * @Author:pengzhilin
     * @Date: 2021/3/20 9:10
     */
    public class Person {
        public void method1(){}
        protected void method2(){}
        void method3(){}
        private void method4(){}
    
    
        public void show(){
            // 同一个类
            method1();
            method2();
            method3();
            method4();
        }
    }
    
    package com.itheima.demo1_权限修饰符;
    
    /**
     * @Author:pengzhilin
     * @Date: 2021/3/20 9:10
     */
    public class Test {
        public static void main(String[] args) {
            Person p = new Person();
            // 同一个包
            p.method1();
            p.method2();
            p.method3();
            // p.method4();// 编译报错
        }
    }
    
    不同包:
    package com.itheima.demo2_权限修饰符;
    
    import com.itheima.demo1_权限修饰符.Person;
    
    /**
     * @Author:pengzhilin
     * @Date: 2021/3/20 9:13
     */
    public class Student extends Person {
    	// 不同包的子类
        public void show(){
            method1();
            method2();
            // method3();// 编译报错
            // method4();// 编译报错
        }
    }
    
    
     */
    public class Test {
        public static void main(String[] args) {
            Person p = new Person();
            // 不同包的无关类
            p.method1();
            // p.method2();// 编译报错
            // p.method3();// 编译报错
            // p.method4();// 编译报错
        }
    }
    
    
开发中的使用
  • 定义类一般使用public
  • 定义成员方法一般使用public
  • 定义成员变量一般使用private
  • 定义构造方法一般使用public

第二章 代码块

第二章 代码块

2.1 构造代码块
  • 格式: {}

  • 位置: 类中,方法外

  • 执行: 每次调用构造方法时,都会执行一次,优先于构造方法执行

  • 使用场景: 统计创建了多少个对象

  • 案例:

    public class Person {
        // 构造代码块
        {
            System.out.println("Person类的构造代码块");
        }
        
        public Person(){
            System.out.println("Person类的空参构造方法");
        }
    
    }
    
    
2.2 静态代码块
  • 格式: static {}

  • 位置: 类中,方法外

  • 执行: 随着类的加载而执行,并且只执行一次

  • 使用场景: 加载驱动,或者放只需要执行一次的代码

  • 案例:

    public class Person {
     	static {
            System.out.println("Person类的静态代码块");
        }   
    }
    
2.3 局部代码块
  • 格式: {}

  • 位置: 方法中

  • 执行: 调用方法时,执行到了局部代码块的位置才执行

  • 使用场景: 节省内存空间,意义不大

  • 案例:

    public class Test {
        public static void main(String[] args) {
            int num1 = 10;
            System.out.println(num1);
            System.out.println("开始");
            // 局部代码块
            {
                int num2 = 20;
                System.out.println("局部代码块,num2:" + num2);
            }
            // System.out.println(num2);// 编译报错,因为超过了num2的作用域
            System.out.println("结束");
        }
    }
    
2.4 注意:
  • 静态代码块优先于构造代码块执行

  • 构造代码块优先于构造方法执行

    public class Person {
        // 静态代码块
        static {
            System.out.println("Person类的静态代码块");
        }
    
        // 构造代码块
        {
            System.out.println("Person类的构造代码块");
        }
    
        public Person(){
            System.out.println("Person类的空参构造方法");
        }
    }
    
    

第三章 Object类

3.1 Object类的概述
  • java.lang.Object类是java语言的根类,所有java类的父类
  • 在java中所有的类都是直接或者间接继承Object类
    • public class Person /*extends Object*/ {} 默认继承Object类
    • public class Student extends Person{} 间接继承Object类
  • Object类中总共有11个成员方法,也就意味着java中所有的类都拥有这11个方法(java的类都会继承Object类)
    • 今天介绍2个方法
    • String toString() 返回该对象的字符串表示。
    • public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。
3.2 toString方法
  • String toString() 返回该对象的字符串表示。

  • 使用场景: 如果打印对象的时候不希望打印的是地址值,那么就重写toString方法

    public class Person {
        String name;
        int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public Person() {
        }
    
        // alt+inset--->toString
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    
    public class Test {
        public static void main(String[] args) {
            /*
                String toString()  返回该对象的字符串表示。
                1.因为java中所有的类都会继承Object类,所以所有的类都拥有toString方法
                2.Object类中的toString方法返回的字符串格式默认为: 类的全名+@+地址值
                3.如果不想使用toString方法的默认返回值,那么就得重写toString方法
                4.直接打印对象名,其实打印的是该对象调用toString方法返回的字符串内容
             */
            // 创建Person对象
            Person p = new Person("张三",18);
            System.out.println(p.toString());// Person{name='张三', age=18}
            System.out.println(p);// Person{name='张三', age=18}
        }
    }
    
3.3 equals方法
  • public boolean equals(Object obj):判断2个对象是否相等。

  • 使用: Object类的equals方法默认比较的是地址值,如果希望比较的不是地址值,而是所有的属性值,那么就按alt+insert,选择equals() and hashCode()重写就行

    public class Person {
        String name;
        int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public Person() {
        }
    
        // alt+inset--->toString
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    
        /*@Override
        public boolean equals(Object obj) {
            // 向下转型
            Person p = (Person) obj;
            return this.name.equals(p.name) && this.age == p.age;
        }*/
    
        // alt+insert-->equals() and hashCode()
        @Override
        public boolean equals(Object o) {
            // 如果2个对象的地址值相对,直接返回true结束方法
            if (this == o) return true;
    
            // 如果参数为null或者2个对象的类不一致,就直接返回false结束方法
            if (o == null || getClass() != o.getClass()) return false;
    
            // 执行到这里,说明要比较的2个对象地址值不同,类型相同
            // 比较2个对象的所有属性值是否相同
            Person person = (Person) o;
            // 比较所有属性
            return age == person.age &&
                    Objects.equals(name, person.name);
        }
    
    }
    
    
    public class Test {
        public static void main(String[] args) {
            /*
                public boolean equals(Object obj):判断2个对象是否相等。
                1.因为java中所有的类都会继承Object类,所以所有的类都拥有equals方法
                2.Object类中的equals方法默认比较的是2个对象的地址值
                3.在开发中,如果2个对象的所有属性值相同,往往认为这2个对象是相等的
                4.如果不希望使用Object类的equals方法比较2个对象,那么就得重写equals方法,指定比较规则
             */
            Person p1 = new Person("张三",18);
            Person p2 = new Person("张三",18);
            // 比较p1和p2是否相等--->没有重写equals方法
            // System.out.println(p1.equals(p2));// false
            // System.out.println(p1 == p2);// false
    
            // 比较p1和p2是否相等--->重写equals方法
             System.out.println(p1.equals(p2));// true
    
        }
    }
    
    
3.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):判断两个对象是否相等。

我们可以查看一下源码,学习一下:

public static boolean equals(Object a, Object b) {  
    return (a == b) || (a != null && a.equals(b));  
}
1.如果2个对象的地址值相同,后面就不执行了(逻辑或短路),而是直接返回true,结束方法
2.如果2个对象的地址值不同:
	2.1 如果a对象的地址值为空,逻辑与后面就不执行了(逻辑与短路),而是直接返回false,结束方法
    2.2 如果a对象的地址值不为空,执行a.equals(b),就是比较2个对象是否相等
public class Test {
    public static void main(String[] args) {
        String a = null;
        String b = "张三";
        // System.out.println(a.equals(b));// 调用的是String类的equals方法,报空指针异常
        System.out.println(Objects.equals(a, b));// false
        System.out.println(Objects.equals("张三", b));// true
        System.out.println(Objects.equals(new String("张三"), b));// true

        /*
            public static boolean equals(Object a, Object b) {
                return (a == b) || (a != null && a.equals(b));
            }
            1.如果2个对象的地址值相同,后面就不执行了(逻辑或短路),而是直接返回true,结束方法
            2.如果2个对象的地址值不同:
                2.1 如果a对象的地址值为空,逻辑与后面就不执行了(逻辑与短路),而是直接返回false,结束方法
                2.2 如果a对象的地址值不为空,执行a.equals(b),就是比较2个对象是否相等
         */
    }
}
3.5 native方法
  • native本地方法的概述

在Object类的源码中定义了 native 修饰的方法, native 修饰的方法称为本地方法。这种方法是没有方法体的,我们查看不了它的实现,所以大家不需要关心该方法如何实现的

  • 当我们需要访问C或C++的代码时,或者访问操作系统的底层类库时,可以使用本地方法实现。

    也就意味着Java可以和其它的编程语言进行交互。

  • 本地方法的作用: 就是当Java调用非Java代码的接口。方法的实现由非Java语言实现,比如C或C++。

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();
    }
    ......
    ......
}

第四章 Date类

3.5 Date类

  • Date类的概述

    • java.util.Date类表示日期,内部精确到毫秒.表示自从标准基准时间(称为“历元(epoch)”,即1970年1月1日00:00:00 GMT)以来的指定毫秒数。
    • 0时区标准基准时间: 1970年1月1日00:00:00
    • 东八区标准基准时间: 1970年1月1日08:00:00
  • Date类中的构造方法

    • public Date Date();当前系统时间对应的日期对象
    • public Date Date(long mills);距离标准基准时间 指定偏移毫秒数 对应的日期对象
  • Date类中的常用方法

    • public long getTime();获取当前日期对象距离标准基准时间的毫秒值
    • public boolean after(Date when) 判断此日期是否在指定日期之后
    • public boolean before(Date when) 判断此日期是否在指定日期之前
    public class Test {
        public static void main(String[] args) {
            // - public Date Date();当前系统时间对应的日期对象
            Date d1 = new Date();
            System.out.println("d1:" + d1);// Sat Mar 20 11:02:51 CST 2021
    
            // - public Date Date(long mills);距离标准基准时间 指定偏移毫秒数 对应的日期对象
            Date d2 = new Date(1000);
            System.out.println("d2:" + d2);// Thu Jan 01 08:00:01 CST 1970
    
            // public long getTime();获取当前日期对象距离标准基准时间的毫秒值
            System.out.println(d1.getTime());
            System.out.println(d2.getTime());// 1000
    
            // - public boolean after(Date when) 判断此日期是否在指定日期之后
            System.out.println(d1.after(d2));// true
    
            // - public boolean before(Date when) 判断此日期是否在指定日期之前
            System.out.println(d1.before(d2));// false
    
    
        }
    }
    

第五章 DateFormat类

3.6 DateFormat类

  • DateFormat类的概述

    • 概述: java.text.DateFormat 该类可以使得在Date对象与String对象之间进行来回转换.
      • 格式化: 按照指定的格式,把Date对象转换为String对象。
      • 解析: 按照指定的格式,把String对象转换为Date对象。
    • 注意: DateFormat是一个抽象类,无法创建对象,应该使用其子类来实现Date和String之间的转换
  • SimpleDateFormat类

    • 概述: java.text.SimpleDateFormat 该类继承DateFormat类,所以该类也可以使得在Date对象与String对象之间进行来回转换.
    • 构造方法:
      • public SimpleDateFormat(String pattern):传入日期指定格式,创建SimpleDateFormat对象.
      • 参数: 指定的日期格式
      • 日期格式的组成元素:
        • y: 年
        • M: 月
        • d: 日
        • H: 时
        • m: 分钟
        • s: 秒
      • 常见的日期格式:
        • yyyy-MM-dd HH:mm:ss
        • yyyy年MM月dd日 HH:mm:ss
  • DateFormat类中的常用方法

    • public String format(Date date):将Date对象格式化为字符串。

    • public Date parse(String source):将字符串解析为Date对象。

    • 注意: 日期格式化对象中指定的日期要和解析的字符串日期格式一致,否则会报解析异常ParseException

      public class Test {
          public static void main(String[] args) throws ParseException {
              // 创建日期格式化对象,指定日期格式为:yyyy-MM-dd HH:mm:ss
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      
              // - public String format(Date date):将Date对象格式化为字符串。
              // 创建当前系统时间的日期对象
              Date nowDate = new Date();
              // Date-->String
              String strDate = sdf.format(nowDate);
              System.out.println("strDate:" + strDate);// 2021-03-20 11:23:59
      
              // - public Date parse(String source):将字符串解析为Date对象。
              // 创建一个表示出生日期的字符串对象
              String birthday = "1996-10-01 08:08:08";
              // String-->Date
              Date birthdayDate = sdf.parse(birthday);
              System.out.println("birthdayDate:" + birthdayDate);// Tue Oct 01 08:08:08 CST 1996
              // 注意: 日期格式化对象中指定的日期要和解析的字符串日期格式一致,否则会报解析异常ParseException
              
          }
      }
      

3.7 日期类练习

需求

  • 键盘输入一个字符串类型的时间,打印你来到世界多少天?

分析

  • 键盘输入一个字符串类型的出生日期
  • 创建日期格式化对象,指定日期格式
  • 把字符串类型的出生日期转换为Date日期对象,转换后就获取该日期对象距离标准基准时间的毫秒值
  • 创建当前系统时间对应的日期对象,然后获取当前系统时间日期对象距离标准基准时间的毫秒值
  • 计算2个毫秒值差,并换算成天数,打印输出

实现

public class Test {
    public static void main(String[] args) throws ParseException {
        // - 键盘输入一个字符串类型的出生日期
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串的出生日期,格式为yyyy-MM-dd:");
        String strBirthday = sc.nextLine();

        // - 创建日期格式化对象,指定日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // - 把字符串类型的出生日期转换为Date日期对象,转换后就获取该日期对象距离标准基准时间的毫秒值
        Date birthdayDate = sdf.parse(strBirthday);
        long time1 = birthdayDate.getTime();

        // - 创建当前系统时间对应的日期对象,然后获取当前系统时间日期对象距离标准基准时间的毫秒值
        long time2 = new Date().getTime();

        // - 计算2个毫秒值差,并换算成天数,打印输出
        System.out.println("出生了" + (time2 - time1) / 1000 / 60 / 60 / 24 + "天");

    }
}

第六章 Calendar类

3.8 Calendar类

  • Calendar类的概述

    • java.util.Calendar类表示一个“日历类”,可以进行日期运算。
    • 特点:
      • Calendar类是一个抽象类,不能创建对象,所以只能使用其子类
      • 子类: GregorianCalendar
  • 获取日历对象:

    • 方式一: 通过 GregorianCalendar 子类的构造方法 不建议

    • 方式二: 通过Calendar类的静态方法getInstance()

      • public static Calendar getInstance();

        public class Test {
            public static void main(String[] args) {
                // public static Calendar getInstance();
                // 获取当前系统时间对应的日历对象
                Calendar cal1 = Calendar.getInstance();
                System.out.println("cal1:" + cal1);
                /*
                    cal1:java.util.GregorianCalendar[time=1616212945561,areFieldsSet=true,
                    areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",
                    offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],
                    firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2021,MONTH=2,WEEK_OF_YEAR=12,
                    WEEK_OF_MONTH=3,DAY_OF_MONTH=20,DAY_OF_YEAR=79,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=3,
                    AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=2,SECOND=25,MILLISECOND=561,ZONE_OFFSET=28800000,
                    DST_OFFSET=0]
        
                 */
            }
        }
        
        
  • Calendar类的注意事项

    • 日历对象中的月份是0-11, 0表示1月,依次类推, 11表示12月

    • 日历对象中的星期是1-7, 1表示星期天,依次类推,7表示星期六

  • Calendar类的常用方法

    • public int get(int field) 获取某个字段的值。

      public class Test1_get {
          public static void main(String[] args) {
              // public int get(int field)  获取某个字段的值。
              // 获取当前时间对应的日历对象
              Calendar cal = Calendar.getInstance();
      
              // 获取cal中年字段的值
              int year = cal.get(Calendar.YEAR);
              System.out.println("year:" + year);// year:2021
      
              // 获取cal中月字段的值
              int month = cal.get(Calendar.MONTH);
              System.out.println("month:" + month);// month:2
      
              System.out.println(cal.get(Calendar.WEEK_OF_YEAR));// 12
          }
      }
      
    • public void set(int field,int value) 设置某个字段的值

      public class Test2_set {
          public static void main(String[] args) {
              // public void set(int field,int value)  设置某个字段的值
              // 获取当前时间对应的日历对象
              Calendar cal = Calendar.getInstance();
              System.out.println(cal);
      
              // 获取cal中年字段的值
              int year = cal.get(Calendar.YEAR);
              System.out.println("year:" + year);// year:2021
      
              // 修改cal对象中的year字段的值,变为2022
              cal.set(Calendar.YEAR,2022);
      
              // 获取cal中年字段的值
              System.out.println("year:" + cal.get(Calendar.YEAR));// year:2022
          }
      }
      
      
    • public void add(int field,int amount) 为某个字段增加/减少指定的值

      public class Test3_add {
          public static void main(String[] args) {
              // public void add(int field,int amount)  为某个字段增加/减少指定的值
              // 获取当前时间对应的日历对象
              Calendar cal = Calendar.getInstance();
              System.out.println(cal);
      
              // 获取cal中年字段的值
              int year = cal.get(Calendar.YEAR);
              System.out.println("year:" + year);// year:2021
      
              // 为年字段的值增加2年
              cal.add(Calendar.YEAR,2);
              System.out.println("year:" + cal.get(Calendar.YEAR));// year:2023
      
              // 为年字段的值减少2年
              cal.add(Calendar.YEAR,-2);
              System.out.println("year:" + cal.get(Calendar.YEAR));// year:2021
          }
      }
      
      
    • void setTime(Date date) 修改当前日历对象表示的时间。

      public class Test4_setTime {
          public static void main(String[] args) throws ParseException {
              // void setTime(Date date) 修改当前日历对象表示的时间。
              String birthdayStr = "1996-10-01";
              // 需求:得到该出生日期对应的日历对象
              // 1.把String类型的日期转换为Date
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
              Date birthdayDate = sdf.parse(birthdayStr);
      
              // 2.获取当前时间对应的日历对象
              Calendar cal = Calendar.getInstance();
      
              // 3.调用日历对象的setTime方法修改日历对象的时间为出生日期的时间
              cal.setTime(birthdayDate);
      
              // 4.获取年,月,日
              System.out.println(cal.get(Calendar.YEAR));// 1996
              System.out.println(cal.get(Calendar.MONTH));// 09
              System.out.println(cal.get(Calendar.DAY_OF_MONTH));// 01
          }
      }
      
    • public boolean after(Object when)判断当前日历对象是否在指定的日历对象之后

    • public boolean before(Object when) 判断当前日历对象是否在指定的日历对象之前

      public class Test4_after_before {
          public static void main(String[] args) throws ParseException {
              // void setTime(Date date) 修改当前日历对象表示的时间。
              String birthdayStr = "1996-10-01";
              // 需求:得到该出生日期对应的日历对象
              // 1.把String类型的日期转换为Date
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
              Date birthdayDate = sdf.parse(birthdayStr);
      
              // 2.获取当前时间对应的日历对象
              Calendar cal = Calendar.getInstance();
      
              // 3.调用日历对象的setTime方法修改日历对象的时间为出生日期的时间
              cal.setTime(birthdayDate);
      
              // 4.获取当前时间对应的日历对象
              Calendar nowCal = Calendar.getInstance();
      
              // 5.比较cal和nowCal
              System.out.println(cal.after(nowCal));// false
              System.out.println(cal.before(nowCal));// true
          }
      }
      
      

第七章 Math类

3.9 Math类

  • Math类的概述

    • 概述: java.lang.Math(类): Math包含执行基本数字运算的方法的工具类。
    • 特点:
      • Math类构造方法被私有修饰,不能创建对象。
      • 操作的时候,都是通过Math类名直接调用该类的静态方法即可。
  • Math类的常用方法

    • public static int abs(int a) 获取参数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 static int max(int a, int b) 返回两个 int 值中较大的一个
    • public static int min(int a, int b) 返回两个 int 值中较小的一个
  • 案例代码

    public class Test {
        public static void main(String[] args) {
            //  - public static int abs(int a)                   获取参数a的绝对值
            System.out.println(Math.abs(10));// 10
            System.out.println(Math.abs(-10));// 10
    
            //  - public static double ceil(double a)            向上取整 (得到大于参数的最小整数)
            System.out.println(Math.ceil(3.14));// 4.0
            System.out.println(Math.ceil(-3.14));// -3.0
    
            //  - public static double floor(double a)           向下取整(得到小于参数的最大整数)
            System.out.println(Math.floor(3.14));// 3.0
            System.out.println(Math.floor(-3.14));// -4.0
    
            //  - public static double pow(double a, double b)   获取a的b次幂
            System.out.println(Math.pow(2, 3));// 8.0
    
            //  - public static long round(double a)             四舍五入取整
            System.out.println(Math.round(3.14));// 3
            System.out.println(Math.round(3.54));// 4
            System.out.println(Math.round(-3.14));// -3
            System.out.println(Math.round(-3.54));// -4
    
            //  - public static int max(int a, int b)            返回两个 int 值中较大的一个
            System.out.println(Math.max(10, 20));// 20
    
            //  - public static int min(int a, int b)            返回两个 int 值中较小的一个
            System.out.println(Math.min(10, 20));// 10
            
        }
    }
    
    

第八章 System

3.10.1 System类

  • System类的概述

    • 概述: java.lang.System类中提供了大量的静态方法,可以获取与系统相关的信息或系统级操作。
    • 特点:
      • System类构造方法被私有修饰,不能创建对象
      • 直接通过System类名调用该类的静态方法
  • System类的常用方法

    • public static void exit(int status) 终止当前运行的Java虚拟机,非零表示异常终止
    • public static long currentTimeMillis() 返回当前时间距离标准基准时间的毫秒值;
  • 案例代码

    public class Test {
        public static void main(String[] args) {
            // - public static void exit(int status)    终止当前运行的Java虚拟机,非零表示异常终止
            System.out.println("开始");
            System.out.println(1);
            // 结束java虚拟机
            // System.exit(0);// 0 表示程序正常结束, 非0 表示程序异常结束
            System.out.println(2);
            System.out.println(3);
            System.out.println("结束");
    
            // - public static long currentTimeMillis() 返回当前时间距离标准基准时间的毫秒值;
            long timeMillis1 = System.currentTimeMillis();
            long timeMillis2 = new Date().getTime();
            System.out.println(timeMillis1 + "," + timeMillis2);
    
    
            // public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
            // 参数1: 源数组
            // 参数2: 用来指定从源数组中那个索引位置开始拷贝元素
            // 参数3: 目标数组
            // 参数4: 用来指定目标数组中那个索引位置开始接收元素
            // 参数5: 用来指定拷贝的元素个数
            int[] arr1 = {1,2,3,4,5,6};
            int[] arr2 = {10,20,30,40,50,60};
            // 需求: 把arr1数组中的2,3,4元素拷贝到arr2数组中,使得arr2数组变为:{10,20,2,3,4,60}
            System.arraycopy(arr1,1,arr2,2,3);
            for (int i = 0; i < arr1.length; i++) {
                System.out.print(arr1[i]+" ");
            }
    
            System.out.println("============");
    
            for (int i = 0; i < arr2.length; i++) {
                System.out.print(arr2[i]+" ");
            }
    
        }
    }
    
    

3.10.2 练习

需求

  • 在控制台输出1-10000,计算这段代码执行了多少毫秒

分析

  • 获取循环开始前,当前时间距离标准基准时间的毫秒值
  • 执行循环
  • 获取循环结束后,当前时间距离标准基准时间的毫秒值
  • 计算2个毫秒值差

实现

public class Test {
    public static void main(String[] args) {
        // - 获取循环开始前,当前时间距离标准基准时间的毫秒值
        long start = System.currentTimeMillis();

        // - 执行循环
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }

        // - 获取循环结束后,当前时间距离标准基准时间的毫秒值
        long end = System.currentTimeMillis();

        // - 计算2个毫秒值差
        System.out.println("总共花了:" + (end - start) + "毫秒");
    }
}

第九章 BigInteger类

3.11 BigInteger类

  • BigInteger类的概述

    • 概述: java.math.BigInteger 表示一个超大的整数

    • 案例:

      public class Test {
          public static void main(String[] args) {
              // int num = 2212345678;// 编译报错,因为等于号右边的数据超过了int类型能表示的数据范围
              // 解决: long numL = 2212345678L;// 正确
              // long num = 22123456782212345678L;// 编译报错,因为等于号右边的数据超过了long类型能表示的数据范围
              // 解决: 使用BigInteger类,表示超大的整数
              BigInteger b = new BigInteger("22123456782212345678"); 
          }
      }
      
  • BigInteger类的构造方法

    • public BigInteger BigInteger(String value); 根据字符串内容创建一个超大的整数对象
    • 注意: 字符串参数一定要传整数的字符串
  • BigInteger类成员方法

    • public BigInteger add(BigInteger value) 加法运算

    • public BigInteger subtract(BigInteger value) 减法运算

    • public BigInteger multiply(BigInteger value) 乘法运算

    • public BigInteger divide(BigInteger value) 除法运算

      public class Test {
          public static void main(String[] args) {
              // int num = 2212345678;// 编译报错,因为等于号右边的数据超过了int类型能表示的数据范围
              // 解决: long numL = 2212345678L;// 正确
              // long num = 22123456782212345678L;// 编译报错,因为等于号右边的数据超过了long类型能表示的数据范围
              // 解决: 使用BigInteger类,表示超大的整数
              BigInteger b1 = new BigInteger("22123456782212345678");
              BigInteger b2 = new BigInteger("10000000000000000000");
      
              // 加法运算
              BigInteger res1 = b1.add(b2);
              System.out.println("res1:"+res1);// 32123456782212345678
      
              // 减法运算
              BigInteger res2 = b1.subtract(b2);
              System.out.println("res2:"+res2);// 12123456782212345678
      
              // 乘法运算
              BigInteger res3 = b1.multiply(b2);
              System.out.println("res3:"+res3);// 221234567822123456780000000000000000000
      
              // 除法运算
              BigInteger res4 = b1.divide(b2);
              System.out.println("res4:"+res4);// 2
      
          }
      }
      

第十章 BigDecimal类

3.12 BigDecimal类

  • BigDecimal类的概述

    • 概述: java.math.BigDecimal类,表示一个超大的小数,并且可以解决小数运算的精度问题

    • 小数运算精度问题演示:

      public class Test1_概述 {
          public static void main(String[] args) {
              // 小数运算的精度问题
              System.out.println(0.09 + 0.01);// 期望的是:0.10,实际不是
              System.out.println(1.0 - 0.32);//  期望的是:0.68,实际不是
              System.out.println(1.015 * 100);// 期望的是:101.5,实际不是
              System.out.println(1.301 / 100);// 期望的是:0.0131,实际不是
          }
      }
      
      
  • BigDecimal类构造方法

    • BigDecimal(double val) 将double类型的数据封装为BigDecimal对象,不推荐使用,因为使用这个依然还是有精度问题
    • BigDecimal(String val) 将 BigDecimal 的字符串表示形式转换为 BigDecimal
  • BigDecimal类常用方法

    • public BigDecimal add(BigDecimal value) 加法运算

    • public BigDecimal subtract(BigDecimal value) 减法运算

    • public BigDecimal multiply(BigDecimal value) 乘法运算

    • public BigDecimal divide(BigDecimal value) 除法运算

    • 注意:如果使用上面的除法运算的方法,遇到除不尽的就会报数学运算异常,得使用下面重载的方法

    • public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) 除法运算

      • 参数1: 除数
      • 参数2: 精确的位数
      • 参数3: 取舍的模式 RoundingMode.HALF_UP: 四舍五入
      public class Test2_BigDecimal的使用 {
          public static void main(String[] args) {
              // - public BigDecimal add(BigDecimal value)  		加法运算
             // BigDecimal b1 = new BigDecimal(0.09);
             // BigDecimal b2 = new BigDecimal(0.01);
             // BigDecimal res1 = b1.add(b2);
             // System.out.println("res1:" + res1);// 得到的结果依然不是0.10,而是一个无限趋近0.10的数
      
              BigDecimal b1 = new BigDecimal("0.09");
              BigDecimal b2 = new BigDecimal("0.01");
              BigDecimal res1 = b1.add(b2);
              System.out.println("res1:" + res1);// 0.10
      
              // - public BigDecimal subtract(BigDecimal value)  		减法运算
              BigDecimal b3 = new BigDecimal("1.0");
              BigDecimal b4 = new BigDecimal("0.32");
              BigDecimal res2 = b3.subtract(b4);
              System.out.println("res2:" + res2);// 0.68
      
              // - public BigDecimal multiply(BigDecimal value)  		乘法运算
              BigDecimal b5 = new BigDecimal("1.015");
              BigDecimal b6 = new BigDecimal("100");
              BigDecimal res3 = b5.multiply(b6);
              System.out.println("res3:" + res3);// 101.500
      
      
              // - public BigDecimal divide(BigDecimal value)  		除法运算
              BigDecimal b7 = new BigDecimal("1.301");
              BigDecimal b8 = new BigDecimal("100");
              BigDecimal res4 = b7.divide(b8);
              System.out.println("res4:" + res4);// 0.01301
      
      
              // 除不尽问题演示
              BigDecimal b9 = new BigDecimal("20");
              BigDecimal b10 = new BigDecimal("3");
              //BigDecimal res5 = b9.divide(b10);// 报异常ArithmeticException
              BigDecimal res5 = b9.divide(b10,2,RoundingMode.HALF_UP);// 报异常ArithmeticException
              System.out.println("res5:" + res5);// 6.67
      
      
          }
      }
      
      

第十一章 Arrays类

3.13 Arrays类

  • Arrays类概述

    • java.util.Arrays类:该类包含用于操作数组的各种静态方法(如排序和搜索)。
  • Arrays类常用方法

    • public static void sort(int[] a):按照数字顺序排列指定的数组 升序
    • public static String toString(int[] a):返回指定数组的内容的字符串表示形式
  • 案例:

    public class Test {
        public static void main(String[] args) {
            // - public static void sort(int[] a):按照数字顺序排列指定的数组 升序
            // - public static String toString(int[] a):返回指定数组的内容的字符串表示形式
            int[] arr = {10, 43, 23, 5, 32, 65, 2, 76};
            System.out.println("排序前数组内容:" + Arrays.toString(arr));// 数组内容:[10, 43, 23, 5, 32, 65, 2, 76]
            // 排序,升序
            Arrays.sort(arr);
            System.out.println("排序后数组内容:" + Arrays.toString(arr));// 数组内容:[2, 5, 10, 23, 32, 43, 65, 76]
    
    
        }
    }
    

第十二章 包装类

3.13 包装类

  • 包装类的概述

    • 概述: 为了更好的维护基本类型数据,java为基本类型创建了对应的引用类型,这些类称为包装类

    • 分类:

      | 基本类型 | 对应的包装类(位于java.lang包中) |
      |   byte   |               Byte                |
      |  short   |               Short               |
      |   int    |               Integer             |
      |   long   |               Long                |
      |  float   |               Float               |
      |  double  |              Double               |
      |   char   |             Character             |
      | boolean  |              Boolean              |
      
      
  • Integer类的使用---->了解

    • 概述: int类型对应包装类,包装一个对象中的原始类型 int 的值

    • 构造方法

      • 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 Test {
          public static void main(String[] args) {
              // Integer的构造方法
              Integer i1 = new Integer(10);// 表示整数10
              Integer i2 = new Integer("10");// 表示整数10
              
              // Integer的静态方法
              Integer i3 = Integer.valueOf(10);// 表示整数10
              Integer i4 = Integer.valueOf("10");// 表示整数10
          }
      }
      
      
  • 拆箱和装箱

    • 装箱: 把基本类型转换为对应的包装类类型---->包装类的构造方法\valueOf静态方法可以实现

    • 拆箱: 把包装类类型转换为对应的基本类型---->包装类的 xx类型Value() 非静态方法实现

    • 案例:

      public class Test {
          public static void main(String[] args) {
              // 装箱: 基本类型---->对应的包装类类型
              // Integer的构造方法
              Integer i1 = new Integer(10);// 表示整数10
      
              // Integer的静态方法
              Integer i2 = Integer.valueOf(10);// 表示整数10
      
      
              // 拆箱: 包装类型类型---->基本类型
              int num1 = i1.intValue();// 10
              int num2 = i2.intValue();// 10
              System.out.println(num1 + num2);// 20
      
          }
      }
      
      
  • 自动装箱和自动拆箱

    • 自动装箱: 基本类型自动转换为对应的包装类类型---->直接把基本类型的值赋值给对应的包装类类型变量

    • 自动拆箱: 包装类类型自动转换为对应的基本类型---->直接把包装类的对象赋值给对应的基本类型的变量

      public class Test {
          public static void main(String[] args) {
              // - 自动装箱: 基本类型自动转换为对应的包装类类型---->直接把基本类型的值赋值给对应的包装类类型变量
              Integer i1 = 10;
              Double d = 3.14;
      
              // - 自动拆箱:  包装类类型自动转换为对应的基本类型---->直接把包装类的对象赋值给对应的基本类型的变量
              int num = i1;
              double numD = d;
              System.out.println(num + 10);//20
          }
      }
      
  • 基本类型与字符串之间的转换

    • 基本类型–>字符串:

      • 方式一: 基本类型的数据 + 空的字符串("")

      • 方式二: 字符串的静态方法public static String valueOf(基本类型的值);

      • 案例:

        public class Test1 {
            public static void main(String[] args) {
                // 基本类型-->字符串:
                //- 方式一:   基本类型的数据 + 空的字符串("")
                int num1 = 100;
                String str1 = num1 + "";
                
                //- 方式二:   字符串的静态方法public static String valueOf(基本类型的值);
                int num2 = 200;
                String str2 = String.valueOf(num2);
                
            }
        }
        
    • 字符串–>基本类型:

      • 方式一: 通过包装类的静态方法valueOf(String s)得到包装类对象,然后包装类对象自动拆箱为基本类型—>除了Character包装类之外,所有包装类都有这个方法

      • 方式二: 通过包装类的静态方法parseXXX类型(String s)得到对应的基本类型—>除了Character包装类之外,所有包装类都有这个方法

        public class Test2 {
            public static void main(String[] args) {
                // 字符串-->基本类型:
                // - 方式一:  通过包装类的静态方法valueOf(String s)得到包装类对象,然后包装类对象自动拆箱为基本类型--->除了Character包装类之外,所有包装类都有这个方法
                Integer i1 = Integer.valueOf("10");
                int num1 = i1;
        
                // 方式二: 通过包装类的静态方法parseXXX类型(String s)得到对应的基本类型--->除了Character包装类之外,所有包装类都有这个方法
                int num2 = Integer.parseInt("20");
                System.out.println(num1+","+num2);// 10,20
        
            }
        }
        
        

总结

必须练习:
	1.理解各个权限修饰符的权限
    2.掌握代码块的使用--->特别是静态代码块
    3.熟练掌握几个api
        3.1 Object类的2个方法,
		3.2 Date与String之间的转换--->SimpleDateFormat
        3.3 BigDecimal类的使用
        3.4 Arrays类的toString方法
        3.5 System类的2个方法
        3.6 Calendar类的常用方法
    4.自动装箱和自动拆箱
    5.基本类型和字符串之间的转换
            
- 能够说出每种权限修饰符的作用
  			 同一个类		同一个包		不同包的父子类			不同包的无关类
    public   	√				√				√					√
    protected	√				√				√					×
    默认		   √			   √               ×                   ×
    private     √               ×               ×                   ×    
            
- 能够说出Object类的特点
   Object类是java中所有类的父类\根类,所有类都用有Object类中的11个方法
            
- 能够重写Object类的toString方法
    alt+insert--->toStrig()
    如果打印对象的时候不希望打印的是地址值,那么就重写toString方法
            
- 能够重写Object类的equals方法
   Object类的equals方法默认比较的是地址值,如果希望比较的不是地址值,而是所有的属性值,那么就按alt+insert,选择equals() and hashCode()重写就行
   alt+insert---> equals() and hashCode()
            
- 能够使用日期类输出当前日期
    public Date Date();

- 能够使用将日期格式化为字符串的方法
   SimpleDateFormat: public String format(Date date);

- 能够使用将字符串转换成日期的方法
    SimpleDateFormat: public Date parse(String date);

- 能够使用Calendar类的get、set、add方法计算日期
  public int get(int field)  获取某个字段的值。
  public void set(int field,int value)  修改某个字段的值。
  public void add(int field,int value)  增加或者减少某个字段的值。
    
- 能够使用Math类对某个浮点数进行四舍五入取整
   public static long round(double a)             四舍五入取整
    
- 能够使用System类获取当前系统毫秒值
  public static long currentTimeMillis() 返回当前时间距离标准基准时间的毫秒值;

- 能够说出BigDecimal可以解决的问题
    小数运算精度问题,表示超大的小数
    
- 能够说出自动装箱、自动拆箱的概念
   - 自动装箱: 基本类型自动转换为对应的包装类类型---->直接把基本类型的值赋值给对应的包装类类型变量
   - 自动拆箱:  包装类类型自动转换为对应的基本类型---->直接把包装类的对象赋值给对应的基本类型的变量

- 能够将基本类型转换为对应的字符串
     基本类型的数据 + 空的字符串("")
       
- 能够将字符串转换为对应的基本类型
      包装类的静态方法:  parseXXX类型(String s)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值