常用类及其方法

目录

目录

1. 枚举

2. 包装类

2.1 构造方法

2.2 包装类转基本数据类型

2.3 基本数据类型转包装类

2.4 基本类型转字符串

3. 包装类面试题

4. Math类

5. Random类

6. System类

8. String

9. String类面试题

10. StringBuffer 和 StringBuilder

11. final,finally,finalize() 的区别?

12. 日期相关的API

12.1. java.util.Date

12.3. Calendar 类

12.4 LocalDate(JDK8)

 12.5. LocalTime(JDK8)

13. BigInteger 和 BigDecimal

1. 枚举

枚举类是JDK1.5才添加的新特性

枚举类中默认为全局静态变量

所有的枚举类都默认继承自Java.long.Enum类,所以不能再继承其他的类,但可以实现接口

枚举类不能new 对象,只能通过类名加点访问枚举类中的数据

枚举类都自带一个values方法,此方法表示获取到枚举类中所有的数据,返回值为数组

public enum Employee implements  Work{
    WORKER("sz005","赵四",20,3200),
    MANAGER("sz002","大拿",30,18000),
    CEO("sz001","富贵",15,1000000),
    CTO("sz003","刘能",55,56222);

    private String name;
    private String empId;
    private int age;
    private double salary;

    Employee(String empId,String name,int age,double salary){
        this.empId = empId;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public static Employee getEmployeeById(String empId){
        Employee[] values = Employee.values();
        for(int i = 0;i < values.length;i++){
            if(empId.equals(values[i].empId)){
                return values[i];
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", empId='" + empId + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                "} " + super.toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public void doWork() {
        System.out.println(name + "在工作");
    }
}
package com.atguigu.test1;

public interface Work {
    void doWork();
}
public class TestEmployee {
    public static void main(String[] args) {
       Employee emp1 = Employee.CEO;

        System.out.println(emp1.getName());
        System.out.println(emp1.getEmpId());
        System.out.println(emp1.getSalary());
        System.out.println(emp1.getAge());

        emp1.doWork();

        Employee sz002 = Employee.getEmployeeById("sz002");

        sz002.doWork();

        System.out.println(sz002);
    }
}

2. 包装类

2.1 构造方法

包装类

基本数据类型:byte、short、int、long、float、double、boolean、char

包装类类型:Byte、Short、Integer、Long、Floa、Double、Boolean、Charater

所有的包装类都支持传入一个与之对应的基本类型作为类型作为参数构造实例

除了Character类之外,其他的包装类还支持传入一个字符串结构实例

注意:字符串必须解析为正确的数据

Boolean 类的构造方法,使用String作为参数

不区分大小写,内容true则为true,其他的一律为false,包括null

public class TestWarpClassConstructor {
    public static void main(String[] args) {
        Byte b1 = new Byte((byte) 12);
        System.out.println("b1 = " + b1);

        Byte b2 = new Byte("120");
        System.out.println("b2 = " + b2);

        Short s1 = new Short((short) 223);
        System.out.println("s1 = " + s1);

        Short s2 = new Short("5623");
        System.out.println("s2 = " + s2);

        Integer i1 = new Integer(0123);
        System.out.println("i1 = " + i1);

        Integer i2 = new Integer("04512");
        System.out.println("i2 = " + i2);

        Long l1 = new Long(1245);
        System.out.println("l1 = " + l1);

        Long l2 = new Long("89445");
        System.out.println("l2 = " + l2);

        Float f1 = new Float(3.5F);
        System.out.println("f1 = " + f1);
        Float f2 = new Float(3.5);
        System.out.println("f2 = " + f2);
        Float f3 = new Float("3.52F");
        System.out.println("f3 = " + f3);

        Double d1 = new Double(3.2);
        System.out.println("d1 = " + d1);

        Double d2 = new Double("3.6");
        System.out.println("d2 = " + d2);

        Character ch1 = new Character('a');

        Boolean bl1 = new Boolean(true);
        Boolean bl2 = new Boolean(false);

        Boolean bl3 = new Boolean("tRUe");
        System.out.println("bl3 = " + bl3);

        Boolean bl4 = new Boolean("abc hello world");
        System.out.println(bl4);

        Boolean bl5 = new Boolean(null);
        System.out.println("bl5 = " + bl5);
    }
}

2.2 包装类转基本数据类型

xxxValue():每一个包装类都有一个这样的方法,用于将包装类对象转换为基本数据类型

public class TestXxxValue {
    public static void main(String[] args) {
        Byte b1 = new Byte("123");
        byte b = b1.byteValue();
        System.out.println("b = " + b);

        Short s1 = new Short("1234");
        short i = s1.shortValue();
        System.out.println("i = " + i);

        Integer i1 = new Integer(324353);
        int i2 = i1.intValue();
        System.out.println("i2 = " + i2);

        Long l1 = new Long("6762321");
        long l = l1.longValue();
        System.out.println("l = " + l);

        Float f1 = new Float(3.5F);
        float v = f1.floatValue();
        System.out.println("v = " + v);

        Double d1 = new Double("895612");
        double v1 = d1.doubleValue();
        System.out.println("v1 = " + v1);

        Character ch1 = new Character('a');
        char c = ch1.charValue();

        System.out.println("c = " + c);

        Boolean bl1 = new Boolean("fsafewwrw");
        boolean b2 = bl1.booleanValue();
        System.out.println("b2 = " + b2);
    }
}

2.3 基本数据类型转包装类

value()方法:每一个包装类都提供有这个方法,用于将基本数据类型转换为包装类

public class TestValueOf {
    public static void main(String[] args) {
        Byte aByte = Byte.valueOf("123");
        System.out.println("aByte = " + aByte);

        Short aShort = Short.valueOf("234");
        System.out.println("aShort = " + aShort);

        Integer integer = Integer.valueOf("12423");
        System.out.println("integer = " + integer);

        Long aLong = Long.valueOf("6778");
        System.out.println("aLong = " + aLong);

        Float aFloat = Float.valueOf("3.5F");
        System.out.println("aFloat = " + aFloat);

        Double aDouble = Double.valueOf("3.5");
        System.out.println("aDouble = " + aDouble);

        Boolean aBoolean = Boolean.valueOf(false);
        System.out.println("aBoolean = " + aBoolean);

        Character a = Character.valueOf('a');
        System.out.println("a = " + a);
    }
}

2.4 基本类型转字符串

toString:以字符串形式返回包装对象表示的基本数据类型数据(基本类型--->字符串)

public class TestParseXxx {
    public static void main(String[] args) {
        byte b = Byte.parseByte("123");
        System.out.println("b = " + b);

        short i = Short.parseShort("123");
        System.out.println("i = " + i);

        int i1 = Integer.parseInt("1234214");
        System.out.println("i1 = " + i1);

        long l = Long.parseLong("2142142");
        System.out.println("l = " + l);


        float v = Float.parseFloat("3.5F");
        System.out.println("v = " + v);

        double v1 = Double.parseDouble("2134214.5");
        System.out.println("v1 = " + v1);

        boolean abc = Boolean.parseBoolean("abc");
        System.out.println("abc = " + abc);
    }
}

3. 包装类面试题

自动装箱和拆箱:

从JDK1.5开始 允许包装类对象 和 基本数据类型混合运算 这个过程就属于装箱和拆箱

装箱:将基本数据类型自动转换为包装类对象

拆箱:将包装类对象自动转换为基本数据类型

回顾==和equals的区别?

包装类面试题: Short,Integer,Long,Character 四个包装类直接使用=号赋值

将实现自动装箱 底层会帮我们自动调用 valueOf方法 此方法实现如下

如果取值范围在byte以内 则两个取值相同的对象 ==比较为true 因为是从缓存数组中取出的同一个对象 地址相同

如果取值范围超出byte 则两个取值相同的对象==比较为false 因为是new的新的对象

public class TestInterview {
    public static void main(String[] args) {
        Integer.valueOf(20);

        Integer i1 = 20; // 装箱  Integer.valueOf(20);
        int i2 = i1; // 拆箱

        System.out.println("--------------------------------------------------------------");
        Integer a = -129;
        Integer b = -129;
        System.out.println(a == b);

        Integer c = 200;
        Integer d = 200;
        System.out.println(c == d);

        Short a1 = -129;
        Short b1 = -129;

        Short c1 = 200;
        Short d1 = 200;

        Byte bb1 =   127;
        Byte bb2 =   127;

        System.out.println(bb1 == bb2);
    }
}

4. Math类

Math类,数学工具类,提供有常用的数学运算方法和两个静态常量E  PI

public class TestMath {
    public static void main(String[] args) {
        System.out.println(Math.E);
        System.out.println(Math.PI);

        System.out.println(Math.abs(-333));
        System.out.println(Math.ceil(3.3));
        System.out.println(Math.floor(3.9));
        System.out.println(Math.round(3.6));
        System.out.println(Math.max(100, 200));
        System.out.println(Math.min(100, 220));
        System.out.println((int)(Math.random() * 100));

        // 17以内的随机数
        System.out.println((int)(Math.random() * 17));

        // 随机生成100以内的整数 提示用户猜  并且提示猜大了或者小了 直到猜对 打印猜了几次
    }
}

5. Random类

Random类,此类专门用于各种类型的随机数据

import java.util.Random;

/**
 * @author WHD
 * @description TODO
 * @date 2023/4/17 14:13
 *  Random 类  此类专门用于各种类型的随机数据
 */
public class TestRandom {
    public static void main(String[] args) {
        Random random = new Random();
        System.out.println(random.nextBoolean());
        System.out.println(random.nextInt());
        System.out.println(random.nextInt(100));
        System.out.println(random.nextDouble());
        System.out.println(random.nextLong());
        System.out.println(random.nextFloat());
    }
}

6. System类

System:系统类,提供的有关于系统相关的各种方法

arraycopy()复制数组

currentTimeMillis()获取系统当前时间的毫米数,从1970年1月1日0点0分0秒到目前

exit(int status) 退出JVM虚拟机

gc() garbage collection 运行垃圾回收器

getProperties() 获取所有系统相关的属性

getProperty(String key) 根据键获得到对应的属性值

public class TestSystem {
    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());

        Student stu1 = new Student();

        stu1 = null;

        System.gc();

        System.out.println(stu1);

        Properties properties = System.getProperties();

        System.out.println(properties.getProperty("user.name"));
        System.out.println(properties.getProperty("java.version"));
        System.out.println(properties.getProperty("file.encoding"));
        //…… 关于系统信息的属性 键 非常多 但是不需要记忆
        properties.list(System.out); // 借助于打印流 将所有的属性信息打印

        System.exit(220);
        System.out.println("程序结束");
    }
}

7. Runtime类

Runtime类:此类提供了用于获取Java虚拟机运行过程中信息的各种方法

exec(String command) 执行本地的一个可执行文件

exit(int status) 退出JVM虚拟机

freeMemory() 获取空闲内存

gc() 运行垃圾回收器

getRuntime() 获取当前类实例

maxMemory() 获取最大内存

totalMemory() 获取总内存

public class TestRuntime {
    public static void main(String[] args) throws IOException {
        Runtime runtime = Runtime.getRuntime();

        System.out.println("空闲内存:" + runtime.freeMemory() / 1024 / 1024); // 字节
        System.out.println("最大内存:" + runtime.maxMemory() / 1024  / 1024); // 字节
        System.out.println("总内存:" + runtime.totalMemory() / 1024  / 1024); // 字节

        runtime.exec("D:\\funny\\10秒让整个屏幕开满玫瑰花\\点我.exe");

        runtime.exit(1);
        runtime.gc();
    }
}

8. String

length() 获取字符串的长度

equals() 比较字符串内容

equalsIgnoreCase() 忽略大小写比较

toLowerCase() 转换为小写

toUpperCase() 转换为大写

concat() 拼接字符串 indexOf(int ch) 搜索第一个出现的字符ch(或字符串value),如果没有找到,返回-1

indexOf(String str) 搜索第一个出现的字符ch(或字符串value),如果没有找到,返回-1

lastIndexOf(int ch) 搜索最后一个出现的字符ch(或字符串value),如果没有找到,返回-1

lastIndexOf(String value) 搜索最后一个出现的字符ch(或字符串value),如果没有找到,返回-1

substring(int index) 从指定下标位置截取字符串 截取到末尾

substring(int beginIndex, int endIndex) 从指定位置开始 到指定位置结束 包前不包后

trim() 去除字符串首尾的空格

split(String regx) : 根据指定的条件拆分字符串 返回值为字符串数组

charAt(int index) 返回指定下标位置的char元素

contains(String str) 判断字符串中是否包含另外一个字符串 包含为true 不包含为false

startsWith(String str) : 判断字符串是否以某一个字符串开头

endsWith(String str) : 判断字符串是否以某一个字符串结尾

replace(String oldStr,String newStr) 替换字符串

toCharArray() 将字符串转为char数组

9. String类面试题

String对象是不可变对象 任何对字符串内容的改变都会产生新的对象 *

为什么String对象不可变呢?

1.因为String类是使用final修饰 表示此类不能被继承

2.String类底层是以char数组维护每一个字符串对象的 而此char数组是使用final修饰的

3.用于保存字符串的char数组 是使用private修饰的 外界无法访问

因为String类是不可变对象 所以当我们需要频繁的修改一个字符串内容的情况 不推荐使用String

推荐使用StringBuffer 或者 StringBuilder

有没有什么方法可以使String对象可变?

有 使用反射可以改变字符串内容

10. StringBuffer 和 StringBuilder

String、StringBuffer、StringBuilder的区别?

String是不可变字符串对象

StringBuffer和StringBuilder是可变自字符串对象

StringBuffer 线程安全 源自于JDK1.0

StringBuilder 线程不安全 源自于JDK1.5

public class TestString {
    public static void main(String[] args) {
        String str1 = "abc";
        str1 += "hello";

        String condition = "电脑";

        condition += "联想";

        condition += "工作站";

        condition += "64GB";

        condition += "8GB";

        condition += "4090TI";

        System.out.println(condition);

        StringBuilder sb = new StringBuilder();

        sb.append("abc");
        sb.append(false);
        sb.append('a');
        sb.append(123);

        System.out.println(sb);

        sb.delete(0, 3);

        System.out.println(sb);


        sb.insert(3, true);

        System.out.println(sb);


        sb.setCharAt(0, 'A');

        System.out.println("sb = " + sb);

        sb.reverse();

        System.out.println("sb = " + sb);
    }
}

11. final,finally,finalize() 的区别?

final属于Java关键字,用来修饰属性、方法、类

finally属于Java关键字 用于处理异常,表示任何情况下都会执行的代码

finalize()属于Object 类提供的一个方法(相当于C中的析构函数)表示当前对象被垃圾回收将调用此方法

12. 日期相关的API

12.1. java.util.Date

java.util.Date 此类属于日期类 提供有日期时间相关的操作的方法

public class TestDate {
    public static void main(String[] args) {
        Date date1 = new Date();

        System.out.println("年" +  (date1.getYear() + 1900));
        System.out.println("月" + (date1.getMonth() + 1));
        System.out.println("日" + date1.getDate());
        System.out.println("一周中的第几天:" + date1.getDay());
        System.out.println("时:" +  date1.getHours());
        System.out.println("分:" + date1.getMinutes());
        System.out.println("秒:" +  date1.getSeconds());

        System.out.println(date1);
        System.out.println(date1.toString());

        Date date2 = new Date(System.currentTimeMillis());
        System.out.println(date2);

        Date date3 = new Date(56898628915L);
        System.out.println(date3);
    }
}

12.2. SimpleDateFormat类

SimpleDateFormat:此类属于日期格式化类,可以按照我们自定义的格式来格式化日期

SimpleDateFormat():无参构造,会使用默认的日期格式处理日期,22-11-3 下午9:36

SimpleDateFormat(String pattern) : 有参构造 会使用指定的日期格式处理日期

String format(Date date):根据传入的日期对象 将日期转换为字符串

Date parse(String source):根据传入的字符串,将字符串转换为日期对象

public class TestSimpleDateFormat {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf1 = new SimpleDateFormat();

        Date date1 = new Date();

        String format = sdf1.format(date1);

        System.out.println("format = " + format);

        Date parse = sdf1.parse("22-1-11 下午9:46");

        System.out.println("parse = " + parse);

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

        Date parse1 = sdf2.parse("2021年1月11日 12:33:56");

        System.out.println("parse1 = " + parse1);

        String format1 = sdf2.format(parse1);

        System.out.println("format1 = " + format1);
    }
}

12.3. Calendar 类

日历类,提供的有操作日期的常用方法 

public class TestCalendar {

    public static void main(String[] args) {
        Calendar instance = Calendar.getInstance();

        System.out.println(instance.get(Calendar.YEAR) + "年");
        System.out.println(instance.get(Calendar.MONTH) + 1 + "月");
        System.out.println(instance.get(Calendar.DAY_OF_MONTH) + "日");
        System.out.println(instance.get(Calendar.DAY_OF_WEEK) + "一周天数");
        System.out.println(instance.get(Calendar.HOUR) + "时");
        System.out.println(instance.get(Calendar.MINUTE) + "分");
        System.out.println(instance.get(Calendar.SECOND) + "秒");
    }
}

12.4 LocalDate(JDK8)

LocalDate :只包含年月日的日期类

now() : 获取当前时间 返回值为 LocalDate对象 of(int year,int month,int day) : 设置年月日 返回值LocalDate对象

public class TestLocalDate {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        System.out.println(now.getYear());
        System.out.println(now.getMonth());
        System.out.println(now.getDayOfWeek());
        System.out.println(now.getDayOfMonth());
        System.out.println(now.getDayOfYear());

        System.out.println(now);

        LocalDate of = LocalDate.of(1997, 11, 12);
        System.out.println(of.getYear());
        System.out.println(of.getMonth());
        System.out.println(of.getDayOfWeek());
        System.out.println(of.getDayOfMonth());
        System.out.println(of.getDayOfYear());

        System.out.println(of);
    }
}

 12.5. LocalTime(JDK8)

LocalTime : 只包含时分秒的日期类

now() : 获取当前时间 返回值为 LocalTime对象

of(int hours,int minutes,int seconds) : 设置时分秒 返回值LocalTime对象

public class TestLocalTime {
    public static void main(String[] args) {
        LocalTime now = LocalTime.now();

        System.out.println(now.getHour());
        System.out.println(now.getMinute());
        System.out.println(now.getSecond());
        System.out.println(now);

        LocalTime of = LocalTime.of(12, 12, 12);
        System.out.println(of);
    }
}

12.6. LocalDateTime(JDK8)

LocalDateTime 包含年月日 时分秒的日期类

now()获取当前时间 返回值为 LocalDateTime对象

of(int year,int month,int day,int hours,int minutes,int seconds) : 设置年月日时分秒 返回值LocalDateTime对象

public class TestLocalDateTime {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now.getYear());
        System.out.println(now.getMonth());
        System.out.println(now.getDayOfWeek());
        System.out.println(now.getDayOfMonth());
        System.out.println(now.getDayOfYear());
        System.out.println(now.getHour());
        System.out.println(now.getMinute());
        System.out.println(now.getSecond());

        System.out.println(now);

        LocalDateTime of = LocalDateTime.of(2003, 12, 11, 11, 15, 23);
        System.out.println(of);
    }
}

13. BigInteger 和 BigDecimal

BigInteger 支持任意长度的整数

public class TestBigInteger {
    public static void main(String[] args) {
        BigInteger bigInteger1 = new BigInteger("445784578523596532741259635254120359635965206542106352");

        BigInteger bigInteger2 = new BigInteger("56765234525641524515224124532424132");

        System.out.println(bigInteger1.add(bigInteger2));

        System.out.println(bigInteger1.subtract(bigInteger2));

        System.out.println(bigInteger1.multiply(bigInteger2));

        System.out.println(bigInteger1.divide(bigInteger2));
    }
}

BigDecimal 任意长度 任意精度的浮点数

public class TestBigDecimal {
    public static void main(String[] args) {
        BigDecimal bigDecimal1 = new BigDecimal("565765235956415526352635963.649526359641522263526759632");

        BigDecimal bigDecimal2 = new BigDecimal("68986245186526.963410525263520");

        System.out.println(bigDecimal1.add(bigDecimal2));

        System.out.println(bigDecimal1.subtract(bigDecimal2));

        System.out.println(bigDecimal1.multiply(bigDecimal2));

        System.out.println(bigDecimal1.divide(bigDecimal2, 16, RoundingMode.HALF_UP));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值