Java中的常用类及关键字详解

        在Java编程中,有许多常用的类和关键字,每个都有其独特的功能和用法。这篇文章我将详细介绍 BigDecimal 类、Date 类、SimpleDateFormat 类、Calendar 类的常用使用方法,并解释装箱、拆箱、常量池、thisthis()privatesuper 等关键字的作用及使用方法。

1. BigDecimal

  BigDecimal 类用于精确表示任意精度的定点数,特别适用于需要高精度计算的场景,大数据的计算,如金融计算。

常用方法
  • BigDecimal add(BigDecimal augend): 加法
  • BigDecimal subtract(BigDecimal subtrahend): 减法
  • BigDecimal multiply(BigDecimal multiplicand): 乘法
  • BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode): 除法,指定舍入模式
  • BigDecimal setScale(int newScale, RoundingMode roundingMode): 设置小数位数和舍入模式
示例代码
import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalExample {
    public static void main(String[] args) {
        BigDecimal num1 = new BigDecimal("10.25");
        BigDecimal num2 = new BigDecimal("3.75");

        // 加法
        BigDecimal sum = num1.add(num2);
        System.out.println("Sum: " + sum);  // 输出 14.00

        // 减法
        BigDecimal difference = num1.subtract(num2);
        System.out.println("Difference: " + difference);  // 输出 6.50

        // 乘法
        BigDecimal product = num1.multiply(num2);
        System.out.println("Product: " + product);  // 输出 38.4375

        // 除法,指定舍入模式
        BigDecimal quotient = num1.divide(num2, 2, RoundingMode.HALF_UP);
        System.out.println("Quotient: " + quotient);  // 输出 2.73

        // 设置小数位数和舍入模式
        BigDecimal scaledNum = num1.setScale(1, RoundingMode.HALF_UP);
        System.out.println("Scaled Num: " + scaledNum);  // 输出 10.3
    }
}

 

2. Date

   Date 类表示特定的时间点,精确到毫秒。虽然已经被 java.time 包中的类(如 LocalDateTime)取代,但仍然广泛使用。

常用方法
  • long getTime(): 获取自1970年1月1日以来的毫秒数
  • void setTime(long time): 设置时间
示例代码
import java.util.Date;

public class DateExample {
    public static void main(String[] args) {
        // 创建当前时间的 Date 对象
        Date now = new Date();
        System.out.println("Current Date: " + now);

        // 获取时间戳
        long timestamp = now.getTime();
        System.out.println("Timestamp: " + timestamp);

        // 设置时间
        now.setTime(timestamp + 1000000);  // 当前时间加1000000毫秒
        System.out.println("Updated Date: " + now);
    }
}
package com.ffyc.date;

import java.util.Date;

/**
 * Date时间类
 */
public class DateDemo {
    public static void main(String[] args) throws InterruptedException {

        Date d = new Date();
        System.out.println("d"+d);

        System.out.println("从1970年到现在的时间:"+d.getTime());

        /*
        10秒倒计时
         */
        Date d1 = new Date();
        long time = d1.getTime()+1000*10;
        System.out.println(d1);
        while(true)
        {
            Date d2 = new Date();
            System.out.println(d2);
//            Thread.sleep(1000);
            if(time == d2.getTime())
            {
                System.out.println("时间到!");
                break;
            }
        }

    }

}

3. SimpleDateFormat

SimpleDateFormat 类用于格式化和解析日期字符串。

常用方法
  • String format(Date date): 将日期格式化为字符串
  • Date parse(String source): 将字符串解析为日期
示例代码
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {
    public static void main(String[] args) {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 格式化日期
        String formattedDate = sdf.format(now);
        System.out.println("Formatted Date: " + formattedDate);

        // 解析日期字符串
        try {
            Date parsedDate = sdf.parse("2024-07-18 14:30:00");
            System.out.println("Parsed Date: " + parsedDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 4. Calendar

Calendar 类用于操作日期和时间。

常用方法
  • void add(int field, int amount): 增加或减少时间
  • int get(int field): 获取特定字段的值
  • void set(int field, int value): 设置特定字段的值
示例代码
import java.util.Calendar;

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

        // 获取当前年、月、日
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("Current Date: " + year + "-" + month + "-" + day);

        // 增加天数
        calendar.add(Calendar.DAY_OF_MONTH, 5);
        System.out.println("Updated Date: " + calendar.get(Calendar.YEAR) + "-" +
                (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH));
    }
}

5.关键字详解

装箱和拆箱
  • 装箱(Boxing):将基本数据类型转换为对应的包装类对象。
  • 拆箱(Unboxing):将包装类对象转换为基本数据类型。
public class BoxingUnboxingExample {
    public static void main(String[] args) {
        // 装箱
        int a = 5;
        Integer aObj = a;  // 自动装箱
        Integer aObjManual = Integer.valueOf(a);  // 手动装箱

        // 拆箱
        Integer bObj = 10;
        int b = bObj;  // 自动拆箱
        int bManual = bObj.intValue();  // 手动拆箱
    }
}
 常量池

        常量池(Constant Pool)是Java虚拟机的一部分,用于存储运行时常量,如字符串字面值和基本类型的常量。在类加载时,这些常量被加载到常量池中。

public class ConstantPoolExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");

        // str1 和 str2 指向常量池中的同一个对象
        System.out.println(str1 == str2);  // 输出 true

        // str3 是一个新的对象,位于堆中
        System.out.println(str1 == str3);  // 输出 false
    }
}
thisthis()
  • this:引用当前对象的实例。
  • this():在构造方法中调用同一个类的另一个构造方法。
public class ThisExample {
    private int x;

    public ThisExample() {
        this(10);  // 调用带参数的构造方法
    }

    public ThisExample(int x) {
        this.x = x;  // 使用 this 引用当前对象的实例变量
    }

    public void setX(int x) {
        this.x = x;  // 使用 this 区分实例变量和参数
    }

    public int getX() {
        return this.x;  // 使用 this 引用当前对象的实例变量
    }
}
 private

   private 关键字用于声明私有成员,只有类内部可以访问。

public class PrivateExample {
    private int data;

    private void display() {
        System.out.println("Data: " + data);
    }

    public void setData(int data) {
        this.data = data;
    }

    public void show() {
        display();  // 类内部可以访问私有方法
    }
}
super

  super 关键字用于调用父类的方法或构造方法。

class Parent {
    public void display() {
        System.out.println("Parent Display");
    }
}

class Child extends Parent {
    @Override
    public void display() {
        super.display();  // 调用父类的方法
        System.out.println("Child Display");
    }
}

public class SuperExample {
    public static void main(String[] args) {
        Child child = new Child();
        child.display();
    }
}

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值