Java常用类
一、基本数据类型的包装类
1.1 概述
Java的包装类是对八种基本数据类型进行封装,使之具有面向对象的特性。基本数据类型没有类的属性,例如方法。这些包装类分为两类,一种是对象型包装类,它不继承任何其他类,是Object的直接子类;另一种是数值型包装类,它继承自Number类。常用的包装类有Character、Number、Boolean等。
Java的设计当初就提供了8种基本数据类型及对应的8种包装数据类型,正是为了更好地实现面向对象编程。尽管Java是一种面向对象编程语言,但其八种基本数据类型并不支持面向对象编程,因为它们不具备“对象”的特性——不携带属性、没有方法可调用。然而,通过使用包装类,我们可以让基本数据类型具备这些特性,从而更好地利用Java的面向对象编程功能。
1.2 分类
Java基本数据类型的包装类有以下几个:
- 1、Byte:字节型,取值范围为-128到127。
- 2、Short:短整型,取值范围为-32768到32767。
- 3、Integer:整型,取值范围为-2147483648到2147483647。
- 4、Long:长整型,取值范围为-9223372036854775808到9223372036854775807。
- 5、Float:单精度浮点型,取值范围为±3.4E-38到±3.4E+38。
- 6、Double:双精度浮点型,取值范围为±1.8E-308到±1.8E+308。
- 7、Character:字符型,取值范围为Unicode字符集中的任意字符。
- 8、Boolean:布尔型,取值为true或false。
二、String类
2.1 概述
Java String类是Java中表示字符串的常用类,它提供了许多用于操作字符串的方法。
2.2 常用方法
以下是一些常用的String类方法:
- 1、length():返回字符串的长度。
- 2、charAt(int index):返回指定索引处的字符。
- 3、substring(int beginIndex, int endIndex):返回从beginIndex到endIndex(不包括endIndex)的子字符串。
- 4、equals(Object obj):比较两个字符串是否相等。
- 5、toLowerCase():将字符串转换为小写形式。
- 6、toUpperCase():将字符串转换为大写形式。
- 7、trim():去除字符串两端的空格。
- 8、concat(String str):将指定的字符串连接到当前字符串的末尾。
- 9、replace(char oldChar, char newChar):将字符串中的旧字符替换为新字符。
- 10、split(String regex):根据给定的正则表达式将字符串分割成子字符串数组。
例如,以下代码演示了如何使用String类的这些方法:
public class StringDemo {
public static void main(String[] args) {
String str = "Hello World!";
int length = str.length(); // 获取字符串长度
char ch = str.charAt(0); // 获取第一个字符
String subStr = str.substring(7, 12); // 获取子字符串
boolean isEqual = str.equals("Hello World!"); // 判断字符串是否相等
String lowerStr = str.toLowerCase(); // 转换为小写形式
String upperStr = str.toUpperCase(); // 转换为大写形式
String trimmedStr = str.trim(); // 去除两端空格
String concatStr = str.concat(" How are you?"); // 连接字符串
String replacedStr = str.replace('o', 'a'); // 替换字符
String[] splitStr = str.split(" "); // 根据空格分割字符串
}
}
2.3 实现格式化显示
在Java中,可以使用String.format()方法或者System.out.printf()方法来实现格式化显示。以下是两种方法的示例:
- 1、使用String.format()方法:
public class FormatDisplay {
public static void main(String[] args) {
int num = 123;
double pi = 3.1415926;
String str = "Hello, World!";
String formattedNum = String.format("整数:%d", num);
String formattedPi = String.format("圆周率:%.2f", pi);
String formattedStr = String.format("字符串:%s", str);
System.out.println(formattedNum);
System.out.println(formattedPi);
System.out.println(formattedStr);
}
}
- 2、使用System.out.printf()方法:
public class FormatDisplay {
public static void main(String[] args) {
int num = 123;
double pi = 3.1415926;
String str = "Hello, World!";
System.out.printf("整数:%d%n", num);
System.out.printf("圆周率:%.2f%n", pi);
System.out.printf("字符串:%s%n", str);
}
}
以上两种方法都可以实现格式化显示,可以根据需要选择合适的方法。
三、StringBuffer类
Java中的StringBuffer类是一个可变的字符序列,它提供了一些方法来操作字符串。与String类相比,StringBuffer类在处理字符串时更加高效,因为它允许在不创建新对象的情况下修改字符串。
以下是一些常用的StringBuffer类方法:
- 1、append():在字符串末尾添加指定的字符或字符串。
- 2、insert():在指定位置插入指定的字符或字符串。
- 3、delete():删除指定位置的字符或子字符串。
- 4、replace():替换指定位置的字符或子字符串。
- 5、reverse():反转字符串。
- 6、length():返回字符串的长度。
- 7、capacity():返回字符串的容量。
- 8、setLength():设置字符串的长度。
- 9、getCharAt():获取指定位置的字符。
- 10、setCharAt():设置指定位置的字符。
- 11、substring():截取指定范围的子字符串。
以下是一个简单的示例,演示如何使用StringBuffer类:
public class StringBufferExample {
public static void main(String[] args) {
// 创建一个StringBuffer对象
StringBuffer sb = new StringBuffer("Hello, World!");
// 在字符串末尾添加" Java"
sb.append(" Java");
System.out.println(sb); // 输出 "Hello, World! Java"
// 在指定位置插入"Java"
sb.insert(7, "Java");
System.out.println(sb); // 输出 "Hello, Java World! Java"
// 删除指定位置的字符
sb.delete(13, 14);
System.out.println(sb); // 输出 "Hello, Java World!"
// 替换指定位置的字符
sb.replace(7, 10, "JVM");
System.out.println(sb); // 输出 "Hello, JVM World!"
// 反转字符串
sb.reverse();
System.out.println(sb); // 输出 "!dlroW ,avaJ olleH"
// 获取字符串长度
int length = sb.length();
System.out.println("Length: " + length); // 输出 "Length: 18"
// 获取字符串容量
int capacity = sb.capacity();
System.out.println("Capacity: " + capacity); // 输出 "Capacity: 26"
// 设置字符串长度
sb.setLength(10);
System.out.println(sb); // 输出 "!dlroW ,avaJ"
// 获取指定位置的字符
char ch = sb.getCharAt(7);
System.out.println("Character at index 7: " + ch); // 输出 "Character at index 7: W"
// 设置指定位置的字符
sb.setCharAt(7, 'w');
System.out.println(sb); // 输出 "!dlrow ,avaJ"
// 截取指定范围的子字符串
String substring = sb.substring(7, 10);
System.out.println("Substring: " + substring); // 输出 "row"
}
}
四、StringBuilder类 与StringBuffer类
StringBuilder类和StringBuffer类都是Java中用于处理字符串的可变字符序列。它们的主要区别在于线程安全性和性能。
-
1、线程安全性:StringBuffer类是线程安全的,因为它的方法都是同步的,这意味着多个线程可以同时访问它而不会产生冲突。而StringBuilder类是非线程安全的,因为它的方法没有同步,因此在多线程环境下使用时需要额外的同步措施。
-
2、性能:由于StringBuffer类的方法是同步的,因此它的性能比StringBuilder类稍慢。如果不需要线程安全,建议使用StringBuilder类来提高性能。
除了上述区别外,StringBuilder类和StringBuffer类具有相同的方法,例如append()、insert()、delete()、reverse()等。因此,在大多数情况下,可以使用StringBuilder类代替StringBuffer类,除非需要线程安全。
五、Math类
Java Math类是Java标准库中的一个用于执行基本数学运算的类。它提供了许多静态方法,如加法、减法、乘法、除法、取余、平方根、指数、对数等。以下是一些常用的Math类方法:
- 1、加法:double add(double a, double b)
- 2、减法:double subtract(double a, double b)
- 3、乘法:double multiply(double a, double b)
- 4、除法:double divide(double a, double b)
- 5、取余:double modulus(double a, double b)
- 6、平方根:double sqrt(double a)
- 7、指数:double exp(double a)
- 8、对数:double log(double a)
- 9、三角函数:double sin(double a), double cos(double a), double tan(double a)
- 10、反三角函数:double asin(double a), double acos(double a), double atan(double a)
- 11、绝对值:double abs(double a)
- 12、最大值:double max(double a, double b)
- 13、最小值:double min(double a, double b)
以下是一个简单的示例,展示了如何使用Math类进行基本的数学运算:
public class MathExample {
public static void main(String[] args) {
double a = 10;
double b = 5;
System.out.println("a + b = " + Math.add(a, b));
System.out.println("a - b = " + Math.subtract(a, b));
System.out.println("a * b = " + Math.multiply(a, b));
System.out.println("a / b = " + Math.divide(a, b));
System.out.println("a % b = " + Math.modulus(a, b));
System.out.println("sqrt(a) = " + Math.sqrt(a));
System.out.println("exp(a) = " + Math.exp(a));
System.out.println("log(a) = " + Math.log(a));
System.out.println("sin(a) = " + Math.sin(a));
System.out.println("cos(a) = " + Math.cos(a));
System.out.println("tan(a) = " + Math.tan(a));
System.out.println("asin(a) = " + Math.asin(a));
System.out.println("acos(a) = " + Math.acos(a));
System.out.println("atan(a) = " + Math.atan(a));
System.out.println("abs(a) = " + Math.abs(a));
System.out.println("max(a, b) = " + Math.max(a, b));
System.out.println("min(a, b) = " + Math.min(a, b));
}
}
六、Date类
Java中的Date类是一个表示日期和时间的类,它位于java.util包中。Date类提供了一些方法来获取和设置日期和时间的各个部分,如年、月、日、时、分、秒等。以下是一些常用的Date类方法:
- 1、构造方法:Date() - 创建一个表示当前日期和时间的Date对象。
- 2、构造方法:Date(long time) - 使用指定的毫秒数创建一个Date对象。
- 3、getYear() - 返回年份,从1900开始计算。
- 4、getMonth() - 返回月份,从0开始计算(0表示1月,1表示2月,依此类推)。
- 5、getDate() - 返回一个月中的某一天。
- 6、getHours() - 返回小时,从0开始计算(0表示午夜,1表示上午,依此类- 推)。
- 7、getMinutes() - 返回分钟,从0开始计算。
- 8、getSeconds() - 返回秒,从0开始计算。
- 9、setYear(int year) - 设置年份。
- 10、setMonth(int month) - 设置月份。
- 11、setDate(int day) - 设置一个月中的某一天。
- 12、setHours(int hour) - 设置小时。
- 13、setMinutes(int minute) - 设置分钟。
- 14、setSeconds(int second) - 设置秒。
- 15、toString() - 返回一个表示日期和时间的字符串。
以下是一个简单的示例,演示如何使用Date类获取和设置日期和时间:
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
// 创建一个表示当前日期和时间的Date对象
Date currentDate = new Date();
System.out.println("当前日期和时间: " + currentDate);
// 获取并打印年、月、日、时、分、秒
int year = currentDate.getYear() + 1900;
int month = currentDate.getMonth() + 1;
int day = currentDate.getDate();
int hours = currentDate.getHours();
int minutes = currentDate.getMinutes();
int seconds = currentDate.getSeconds();
System.out.println("年: " + year + ", 月: " + month + ", 日: " + day + ", 时: " + hours + ", 分: " + minutes + ", 秒: " + seconds);
// 设置新的日期和时间
currentDate.setYear(year - 1);
currentDate.setMonth(month - 1);
currentDate.setDate(day - 1);
currentDate.setHours(hours - 1);
currentDate.setMinutes(minutes - 1);
currentDate.setSeconds(seconds - 1);
System.out.println("更新后的日期和时间: " + currentDate);
}
}
七、SimpleDateFormat类
SimpleDateFormat类是Java中用于格式化和解析日期的类。它提供了一种灵活的方式来定义日期和时间的格式,以便在不同的应用程序中使用。
以下是使用SimpleDateFormat类的示例代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
// 创建一个SimpleDateFormat对象,指定日期格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 获取当前日期
Date currentDate = new Date();
// 将当前日期格式化为字符串
String formattedDate = dateFormat.format(currentDate);
// 输出格式化后的日期
System.out.println("当前日期:" + formattedDate);
// 解析一个日期字符串
String dateString = "2023-07-03";
try {
Date parsedDate = dateFormat.parse(dateString);
System.out.println("解析后的日期:" + parsedDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上述示例中,我们首先创建了一个SimpleDateFormat对象,并指定了日期格式为"yyyy-MM-dd"。然后,我们获取当前日期并将其格式化为字符串。接下来,我们演示了如何解析一个日期字符串。
请注意,在使用SimpleDateFormat类时,需要处理可能出现的异常,例如ParseException。