Advertisement

Java 常用类(String、Math、Date、Calendar和Random)

阅读量:

一、引言

对于Java编程而言,在熟练掌握各类基础组件方面具有重要价值。这类核心组件通常包含大量实用功能,在提高编程效率方面发挥着关键作用。阐述Java语言中几个典型的基础类时钟组件包括字符串处理、数学运算、日期时间管理以及随机数生成等特性,并可以通过实际编码示例清晰展示每个组件的应用场景和操作流程。

二、String

2.1 String 类概述

String 类在 Java 中是最常用且重要的类之一。
用于表示字符串。
在 Java 中认为字符串是不可变的对象。
如果需要更改其内容,
实际上创建了一个新的 String 对象。

2.2 String 类的创建

在 Java 中,创建 String 对象有两种常见的方式:

复制代码
    // 方式一:使用字符串字面量
    String str1 = "Hello";
    
    // 方式二:使用 new 关键字
    String str2 = new String("World");

2.3 String 类的常用方法

2.3.1 length() 方法

length() 方法用于返回字符串的长度。

复制代码
    public class StringLengthExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        int length = str.length();
        System.out.println("字符串的长度是:" + length);
    }
    }
2.3.2 equals() 方法

该方法用于比较两个字符串的内容的一致性。值得注意的是,在此操作中,并非通过==来判断两个字符串对象的引用是否相同。

复制代码
    public class StringEqualsExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = new String("Hello");
        System.out.println("使用 equals() 比较:" + str1.equals(str2));
        System.out.println("使用 == 比较:" + (str1 == str2));
    }
    }
2.3.3 substring() 方法

substring() 方法用于截取字符串的一部分。它有两种重载形式:

复制代码
    public class StringSubstringExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        // 从指定索引开始截取到字符串末尾
        String subStr1 = str.substring(7);
        System.out.println("从索引 7 开始截取的字符串是:" + subStr1);
    
        // 从指定起始索引截取到指定结束索引(不包括结束索引)
        String subStr2 = str.substring(7, 12);
        System.out.println("从索引 7 到索引 12(不包括 12)截取的字符串是:" + subStr2);
    }
    }
2.3.4 indexOf() 方法

indexOf() 方法用于搜索特定字符/字符串在原始字符串中的首次位置。若无法找到,则返回值为 -1。

复制代码
    public class StringIndexOfExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        int index1 = str.indexOf('o');
        System.out.println("字符 'o' 第一次出现的位置是:" + index1);
    
        int index2 = str.indexOf("World");
        System.out.println("字符串 'World' 第一次出现的位置是:" + index2);
    }
    }
2.3.5 replace() 方法

replace() 方法用于执行将给定的指定字符或整个字符串替换为目标字符或字符串的操作。

复制代码
    public class StringReplaceExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String newStr = str.replace('o', 'a');
        System.out.println("将字符 'o' 替换为 'a' 后的字符串是:" + newStr);
    
        String newStr2 = str.replace("World", "Java");
        System.out.println("将字符串 'World' 替换为 'Java' 后的字符串是:" + newStr2);
    }
    }
2.3.6 toUpperCase()toLowerCase() 方法

toUpperCase() 函数用于使字符串的所有字符变为大写形式,并非直接进行大小写的切换操作;而 toLowerCase() 函数则专门负责将整个字符串的所有字母转为小写字体状态。

复制代码
    public class StringCaseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String upperCaseStr = str.toUpperCase();
        System.out.println("转换为大写后的字符串是:" + upperCaseStr);
    
        String lowerCaseStr = str.toLowerCase();
        System.out.println("转换为小写后的字符串是:" + lowerCaseStr);
    }
    }

三、Math

3.1 Math 类概述

Java提供了Math这一工具类,其中包含多种常用的数学运算功能。该类包含了多个静态方法来执行基本计算操作如绝对值计算、平方根求取以及三角函数运算等。因为所有静态的方法无需实例化该类就可以直接调用因此无需构造Math对象即可直接调用这些功能。

3.2 Math 类的常用方法

3.2.1 abs() 方法

abs() 方法用于返回一个数的绝对值。

复制代码
    public class MathAbsExample {
    public static void main(String[] args) {
        int num1 = -10;
        double num2 = -3.14;
        int absNum1 = Math.abs(num1);
        double absNum2 = Math.abs(num2);
        System.out.println("-10 的绝对值是:" + absNum1);
        System.out.println("-3.14 的绝对值是:" + absNum2);
    }
    }
3.2.2 max()min() 方法

max() 方法用于计算两个数的最大数值;min() 方法同样用于计算两个数的最小数值。

复制代码
    public class MathMaxMinExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int max = Math.max(a, b);
        int min = Math.min(a, b);
        System.out.println("10 和 20 中的最大值是:" + max);
        System.out.println("10 和 20 中的最小值是:" + min);
    }
    }
3.2.3 sqrt() 方法

sqrt() 方法用于返回一个数的平方根。

复制代码
    public class MathSqrtExample {
    public static void main(String[] args) {
        double num = 25;
        double sqrt = Math.sqrt(num);
        System.out.println("25 的平方根是:" + sqrt);
    }
    }
3.2.4 pow() 方法

pow() 方法用于返回一个数的指定次幂。

复制代码
    public class MathPowExample {
    public static void main(String[] args) {
        double base = 2;
        double exponent = 3;
        double result = Math.pow(base, exponent);
        System.out.println(base + " 的 " + exponent + " 次幂是:" + result);
    }
    }
3.2.5 random() 方法

random() 方法用于返回一个大于等于 0.0 且小于 1.0 的随机双精度浮点数。

复制代码
    public class MathRandomExample {
    public static void main(String[] args) {
        double randomNum = Math.random();
        System.out.println("生成的随机数是:" + randomNum);
    }
    }

四、Date

4.1 Date 类概述

需要注意的是该包中的\texttt{Date}类专门用来表示特定的时间点,并且能够精确到毫秒单位。值得注意的是,在某些旧代码bases中仍可能遇到该类的应用场景。然而,在大多数现代应用程序中建议采用更为现代的方法来处理日期与时间问题。

4.2 Date 类的创建和常用方法

4.2.1 创建 Date 对象

不仅可以用无需参数构造函数来生成反映当前时间点的 Date 对象,并且还可以通过带有参数的构造函数来生成特定时间点对应的 Date 对象。

复制代码
    import java.util.Date;
    
    public class DateCreationExample {
    public static void main(String[] args) {
        // 创建表示当前时间的 Date 对象
        Date currentDate = new Date();
        System.out.println("当前时间是:" + currentDate);
    
        // 创建指定时间的 Date 对象(已过时,不推荐使用)
        Date specifiedDate = new Date(125, 9, 1); // 年份从 1900 开始计算,月份从 0 开始计算
        System.out.println("指定时间是:" + specifiedDate);
    }
    }
4.2.2 getTime() 方法

getTime() 方法用于返回自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数。

复制代码
    import java.util.Date;
    
    public class DateGetTimeExample {
    public static void main(String[] args) {
        Date date = new Date();
        long time = date.getTime();
        System.out.println("自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数是:" + time);
    }
    }
4.2.3 compareTo() 方法

compareTo() 方法用于比较一对 Date 对象的时间顺序。若当前 Date 位于指定 Date 之前,则会返回负数值;若处于之后位置,则会返回正数值;若与指定 Date 相同,则会返回零值。

复制代码
    import java.util.Date;
    
    public class DateCompareToExample {
    public static void main(String[] args) {
        Date date1 = new Date();
        Date date2 = new Date(date1.getTime() + 1000);
    
        int result = date1.compareTo(date2);
        if (result < 0) {
            System.out.println("date1 在 date2 之前");
        } else if (result > 0) {
            System.out.println("date1 在 date2 之后");
        } else {
            System.out.println("date1 和 date2 相等");
        }
    }
    }

五、Calendar

5.1 Calendar 类概述

该类属于抽象类别,并且包含于 java.util 包内。它专门用于执行日期时间和操作相关计算与管理。可通过调用 Calendar.getInstance() 方法来获取此对象。该对象属于 Calendar 类的一个子类实例,并通常属于 GregorianCalendar 类。

5.2 Calendar 类的常用方法

5.2.1 获取 Calendar 对象
复制代码
    import java.util.Calendar;
    
    public class CalendarGetInstanceExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println("获取的 Calendar 对象是:" + calendar);
    }
    }
5.2.2 获取日期和时间信息

可以使用 Calendar 类的 get() 方法获取年、月、日、时、分、秒等信息。

复制代码
    import java.util.Calendar;
    
    public class CalendarGetExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从 0 开始,需要加 1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
    
        System.out.println("当前日期和时间是:" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
    }
    }
5.2.3 设置日期和时间信息

可以使用 Calendar 类的 set() 方法设置年、月、日、时、分、秒等信息。

复制代码
    import java.util.Calendar;
    
    public class CalendarSetExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2025);
        calendar.set(Calendar.MONTH, Calendar.MAY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
    
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
    
        System.out.println("设置后的日期是:" + year + "-" + month + "-" + day);
    }
    }
5.2.4 日期和时间的计算

可以使用 Calendar 类的 add() 方法进行日期和时间的计算。

复制代码
    import java.util.Calendar;
    
    public class CalendarAddExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        // 增加 10 天
        calendar.add(Calendar.DAY_OF_MONTH, 10);
    
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
    
        System.out.println("增加 10 天后的日期是:" + year + "-" + month + "-" + day);
    }
    }

六、Random

6.1 Random 类概述

Random 类属于 java.util 包,并用作随机数值生成工具。它不仅支持生成多种类型的随机数值,并且包括整数值与浮点数值等不同的类型选择。

6.2 Random 类的常用方法

6.2.1 创建 Random 对象
复制代码
    import java.util.Random;
    
    public class RandomCreationExample {
    public static void main(String[] args) {
        // 创建一个使用默认种子的 Random 对象
        Random random = new Random();
        System.out.println("创建的 Random 对象是:" + random);
    }
    }
6.2.2 生成随机整数

可以使用 Random 类的 nextInt() 方法生成随机整数。

复制代码
    import java.util.Random;
    
    public class RandomIntExample {
    public static void main(String[] args) {
        Random random = new Random();
        // 生成一个随机整数
        int randomInt = random.nextInt();
        System.out.println("生成的随机整数是:" + randomInt);
    
        // 生成一个 0 到 9 之间的随机整数
        int randomIntRange = random.nextInt(10);
        System.out.println("生成的 0 到 9 之间的随机整数是:" + randomIntRange);
    }
    }
6.2.3 生成随机浮点数

可以使用 Random 类的 nextDouble() 方法生成随机双精度浮点数。

复制代码
    import java.util.Random;
    
    public class RandomDoubleExample {
    public static void main(String[] args) {
        Random random = new Random();
        double randomDouble = random.nextDouble();
        System.out.println("生成的随机双精度浮点数是:" + randomDouble);
    }
    }

七、总结

系统性地阐述了Java中几个核心类及其应用背景。
如String、Math、Date、Calendar及Random等常用类。
其中String类提供了强大的字符串操作功能,
Math类集成了基本数学运算功能,
而Date和Calendar主要用于处理日期时间和日历功能,
Random则用于生成随机数值。
熟练掌握这些核心类及其使用方法对于提高Java程序开发效率具有重要意义。
在实际编程过程中,
开发者应根据具体需求选择合适的工具库,
同时需注意版本兼容性和方法规范的遵守。

全部评论 (0)

还没有任何评论哟~