Skip to main content

第四课:常用类

Java 中有许多常用的 类

(一) Number 类

Java 提供了一系列的 包装类(Wrapper Class),用于将 基本数据类型intdouble 等)转换为对象 这些包装类都继承自 Number 类。 这个包已经内置,不需要再 import。

1. 常见的包装类

包装类对应的基本类型
Bytebyte
Shortshort
Integerint
Longlong
Floatfloat
Doubledouble
Characterchar
Booleanboolean

2. 自动装箱与拆箱

自动装箱(Autoboxing):基本数据类型 ---> 对应的包装类对象 自动拆箱(Unboxing): 包装类对象 ---> 基本数据类型

示例

public class Temp{
    public static void main(String[] args) {
        Integer x = 5;  // 自动装箱
        x = x + 10;     // x 先拆箱,加 10 后再装箱
        System.out.println(x);  // 输出 15
    }
}

运行结果

15

3. Number 类的常用方法

Number 类的常用方法如下:

方法描述
xxxValue()Number 对象转换为 xxx 数据类型
compareTo()比较两个 Number 对象
equals()判断 Number 对象是否相等
valueOf()将基本类型转换为包装类
toString()返回 Number 对象的字符串表示
parseInt()将字符串解析为 int 类型

示例

public class NumberExample {
    public static void main(String[] args) {
        Integer num1 = Integer.valueOf(10);  // 基本类型转换为包装类
        int num2 = num1.intValue();  // 拆箱
        System.out.println("num1: " + num1);
        System.out.println("num2: " + num2);
        System.out.println("num1.equals(10): " + num1.equals(10));
        System.out.println("num1.compareTo(5): " + num1.compareTo(5));  // 大于返回正数
    }
}

输出

num1: 10
num2: 10
num1.equals(10): true
num1.compareTo(5): 1

(二) Math 类

Java Math 类提供了一系列用于数学计算的方法,这些方法都是 static 静态方法,可以直接调用。

1. 常见方法

方法描述
abs(x)计算 x 的绝对值
ceil(x)返回大于等于 x 的最小整数(向上取整)
floor(x)返回小于等于 x 的最大整数(向下取整)
rint(x)返回最接近 x 的整数(返回 double
round(x)x 进行四舍五入(返回 intlong
min(x, y)返回 xy 中的最小值
max(x, y)返回 xy 中的最大值
sqrt(x)返回 x 的平方根
pow(x, y)计算 xy 次方
exp(x)计算 e^x
log(x)计算 x 的自然对数
random()生成一个 [0,1) 之间的随机数
toDegrees(x)将弧度转换为角度
toRadians(x)将角度转换为弧度

示例

public class MathExample {
    public static void main(String[] args) {
        System.out.println("90度的正弦值:" + Math.sin(Math.PI / 2));
        System.out.println("0度的余弦值:" + Math.cos(0));
        System.out.println("60度的正切值:" + Math.tan(Math.PI / 3));
        System.out.println("π/2的角度值:" + Math.toDegrees(Math.PI / 2));
        System.out.println("e 的 2 次方:" + Math.exp(2));
        System.out.println("log(10):" + Math.log(10));
        System.out.println("2^3:" + Math.pow(2, 3));
        System.out.println("随机数:" + Math.random());
    }
}

运行结果(示例输出)

90度的正弦值:1.0
0度的余弦值:1.0
60度的正切值:1.7320508075688767
π/2的角度值:90.0
e 的 2 次方:7.3890560989306495
log(10):2.302585092994046
2^3:8.0
随机数:0.847382674816738

2. floor、round 和 ceil 方法的区别

输入值Math.floor(x)Math.round(x)Math.ceil(x)
1.41.012.0
1.51.022.0
1.61.022.0
-1.4-2.0-1-1.0
-1.5-2.0-1-1.0
-1.6-2.0-2-1.0

示例

public class RoundExample {
    public static void main(String[] args) {
        double[] nums = { 1.4, 1.5, 1.6, -1.4, -1.5, -1.6 };
        for (double num : nums) {
            System.out.println("Math.floor(" + num + ")=" + Math.floor(num));
            System.out.println("Math.round(" + num + ")=" + Math.round(num));
            System.out.println("Math.ceil(" + num + ")=" + Math.ceil(num));
            System.out.println();
        }
    }
}

运行结果

Math.floor(1.4)=1.0
Math.round(1.4)=1
Math.ceil(1.4)=2.0

Math.floor(1.5)=1.0
Math.round(1.5)=2
Math.ceil(1.5)=2.0

Math.floor(1.6)=1.0
Math.round(1.6)=2
Math.ceil(1.6)=2.0

Math.floor(-1.4)=-2.0
Math.round(-1.4)=-1
Math.ceil(-1.4)=-1.0

Math.floor(-1.5)=-2.0
Math.round(-1.5)=-1
Math.ceil(-1.5)=-1.0

Math.floor(-1.6)=-2.0
Math.round(-1.6)=-2
Math.ceil(-1.6)=-1.0

(三)Character 类

Character 类用于对 单个字符 进行操作,封装了 char 类型,并提供了一系列方法来操作字符。

1. Character 的自动装箱与拆箱

和之前一样,Java 自动装箱(Autoboxing)拆箱(Unboxing) 适用于 Character 类:

public class AutoBoxingExample {
    public static void main(String[] args) {
        Character ch = 'A';  // 自动装箱
        char c = ch;         // 自动拆箱

        System.out.println("Character对象: " + ch);
        System.out.println("拆箱后的 char: " + c);
    }
}

输出:

Character对象: A
拆箱后的 char: A

2. Character 类的常用方法

装类,可以使用 Character 来存储和操作字符数据。

方法描述示例
isLetter(char ch)判断字符是否为字母Character.isLetter('A') // true
isDigit(char ch)判断字符是否为数字Character.isDigit('9') // true
isWhitespace(char ch)判断字符是否为空白字符Character.isWhitespace(' ') // true
isUpperCase(char ch)判断字符是否是大写字母Character.isUpperCase('A') // true
isLowerCase(char ch)判断字符是否是小写字母Character.isLowerCase('a') // true
toUpperCase(char ch)转换为大写字母Character.toUpperCase('a') // 'A'
toLowerCase(char ch)转换为小写字母Character.toLowerCase('A') // 'a'
toString(char ch)将字符转换为字符串Character.toString('a') // "a"

示例

public class TestCharacter {
    public static void main(String[] args) {
        char ch = 'a';    // 自动装箱

        // 判断字符类型
        System.out.println(Character.isLetter(ch));   // true
        System.out.println(Character.isDigit(ch));    // false
        System.out.println(Character.isWhitespace(' ')); // true
        System.out.println(Character.isUpperCase(ch)); // false
        System.out.println(Character.isLowerCase(ch)); // true

        // 字母大小写转换
        System.out.println(Character.toUpperCase(ch)); // 'A'
        System.out.println(Character.toLowerCase('Z')); // 'z'

        // 转换为字符串
        System.out.println(Character.toString(ch)); // "a"
    }
}

3. Character 支持的转义序列

在 Java 中,某些特殊字符需要使用 转义序列(Escape Sequences)。

转义序列描述
\t插入 tab
\b插入 退格
\n插入 换行
\r插入 回车
\f插入 换页符
\'插入 单引号 '
\"插入 双引号 "
\\插入 反斜杠 \

示例:输出包含双引号的字符串

public class EscapeTest {
    public static void main(String[] args) {
        System.out.println("访问\"菜鸟教程!\"");
    }
}

输出:

访问"菜鸟教程!"

示例:检查输入是否为数字

import java.util.Scanner;

public class CheckDigit {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一个字符: ");
        char ch = scanner.next().charAt(0);

        if (Character.isDigit(ch)) {
            System.out.println("你输入的是一个数字!");
        } else {
            System.out.println("你输入的不是数字!");
        }
    }
}

(四)String 类

String 类用于表示字符串,它是 不可变(immutable)的,即一旦创建,内容就无法修改

1. String 的创建

Java 中创建字符串有 两种方式

(1) 直接使用字符串字面量(推荐)

String str = "Runoob";
  • 这种方式的字符串存储在 字符串池(String Pool)中,相同的字符串只存储一份,可以提高性能。

(2) 使用 new 关键字(不推荐)

String str2 = new String("Runoob");
  • new 创建的字符串存储在 堆内存 中,每次都会创建新的 String 对象,即使内容相同,性能较低。

两种创建方式的区别

String s1 = "Runoob";        // 存在字符串池中
String s2 = "Runoob";        // 复用 s1,s1 == s2
String s3 = s1;              // s1 == s3
String s4 = new String("Runoob"); // 堆内存中创建新的字符串
String s5 = new String("Runoob"); // 再次创建新的字符串
  • s1 == s2s1 == s3true(因为指向同一个字符串池对象)。
  • s4 == s5false(因为 new 创建了新的对象)。

示例

public class StringCompare {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = new String("hello");

        System.out.println(s1 == s2);   // true(因为在字符串池中)
        System.out.println(s1 == s3);   // false(因为 s3 是 new 创建的)
        System.out.println(s1.equals(s3)); // true(比较内容)
    }
}
  • == 比较的是 内存地址,只有指向同一个对象时才返回 true
  • equals() 比较的是 字符串内容,内容相同就返回 true

2. String 不可变性

String 对象是不可变的,即创建后无法更改其内容。例如:

String s = "hello";
s.concat(" world");
System.out.println(s); // 仍然输出 "hello"
  • concat(" world") 创建了新的字符串,原来的 s 没有改变。

3. String 的常见操作

(1) 获取字符串长度

String site = "www.runoob.com";
System.out.println(site.length());  // 输出 14

(2) 连接字符串

String s1 = "Hello, ";
String s2 = "Java!";
String s3 = s1.concat(s2);  // 使用 concat() 方法
System.out.println(s3);      // 输出: Hello, Java!

也可以使用 + 连接:

String s = "Hello" + ", Java!";
System.out.println(s);  // Hello, Java!

(3) 字符串格式化

可以使用 format() 方法:

String result = String.format("浮点数: %.2f, 整数: %d, 字符串: %s", 3.14159, 42, "Hello");
System.out.println(result);

4. String 类的常用方法

方法描述示例
char charAt(int index)返回指定索引处的字符"Java".charAt(1) // 'a'
int length()返回字符串的长度"Java".length() // 4
boolean equals(Object anObject)比较字符串内容是否相等"hello".equals("Hello") // false
boolean equalsIgnoreCase(String anotherString)忽略大小写比较"hello".equalsIgnoreCase("Hello") // true
int compareTo(String anotherString)按字典顺序比较字符串"apple".compareTo("banana") // -1
boolean contains(CharSequence s)判断是否包含子串"hello".contains("ll") // true
boolean startsWith(String prefix)是否以指定前缀开始"hello".startsWith("he") // true
boolean endsWith(String suffix)是否以指定后缀结束"hello".endsWith("lo") // true
String toUpperCase()转换为大写"java".toUpperCase() // "JAVA"
String toLowerCase()转换为小写"JAVA".toLowerCase() // "java"
String trim()去除前后空格" hello ".trim() // "hello"
String substring(int beginIndex, int endIndex)截取子字符串"hello".substring(1, 3) // "el"
String replace(char oldChar, char newChar)替换字符"hello".replace('l', 'x') // "hexxo"
String replaceAll(String regex, String replacement)使用正则替换"hello".replaceAll("l", "x") // "hexxo"
String[] split(String regex)拆分字符串"a,b,c".split(",") // ["a", "b", "c"]

示例

(1) substring() 获取子字符串

public class Test {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String sub = str.substring(7, 12);
        System.out.println(sub);  // 输出 "World"
    }
}

在 java 中,索引从 0 开始。startIndex 是包含的,endIndex 是不包含的。

这里有个空格别忽略了

(2) replace() 替换字符

public class Test {
    public static void main(String[] args) {
        String str = "Java is fun";
        String newStr = str.replace("Java", "Python");
        System.out.println(newStr);  // Python is fun
    }
}

(3) split() 拆分字符串

public class Test {
    public static void main(String[] args) {
        String str = "apple,banana,grape";
        String[] fruits = str.split(",");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

输出:

apple
banana
grape

(五)StringBuffer 和 StringBuilder 类

在 Java 中,String 类是不可变的字符串类,这意味着一旦创建了一个字符串对象,就不能修改它。

如果对字符串进行修改,会创建一个新的 String 对象,这样当 有很多字符串操作时 可能会导致性能问题。

为了避免这种情况,Java 提供了 StringBufferStringBuilder 类来高效地操作字符串。

1. 两者区别

  1. 可变性
    • StringBufferStringBuilder 的对象是可变的,可以多次修改对象本身,而不会创建新的对象。
    • String 是不可变的,每次修改字符串内容都会生成新的 String 对象。
  2. 线程安全性
    • StringBuffer 是线程安全的,它的方法是同步的(即每次只有一个线程可以访问这些方法)。
    • StringBuilder 是非线程安全的,它的方法不是同步的,因此在多线程环境下不保证安全。
  3. 性能
    • 由于 StringBuilder 不进行同步操作,它的性能通常优于 StringBuffer。如果不需要线程安全,建议使用 StringBuilder
  • StringBuilder 示例
public class RunoobTest {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(10);
        sb.append("Runoob..");
        System.out.println(sb);  // 输出 Runoob..
        
        sb.append("!");
        System.out.println(sb);  // 输出 Runoob..!
        
        sb.insert(8, "Java");
        System.out.println(sb);  // 输出 Runoob..Java!
        
        sb.delete(5, 8);
        System.out.println(sb);  // 输出 RunooJava!
    }
}
  • StringBuffer 示例
public class Test {
    public static void main(String[] args) {
        StringBuffer sBuffer = new StringBuffer("菜鸟教程官网:");
        sBuffer.append("www");
        sBuffer.append(".runoob");
        sBuffer.append(".com");
        System.out.println(sBuffer);  // 输出 "菜鸟教程官网:www.runoob.com"
    }
}

2. StringBuffer 类的方法

StringBuffer 类提供了很多用于修改字符串内容的方法,以下是一些常用的方法。

主要方法

序号方法描述方法签名
1将指定的字符串追加到此字符序列public StringBuffer append(String s)
2将此字符序列反转public StringBuffer reverse()
3移除子字符串中的字符public StringBuffer delete(int start, int end)
4在指定位置插入字符串public StringBuffer insert(int offset, String str)
5使用指定字符串替换子字符串中的字符public StringBuffer replace(int start, int end, String str)

其他常用方法

序号方法描述方法签名
1返回当前容量int capacity()
2返回指定索引位置的字符char charAt(int index)
3确保容量至少为指定的最小值void ensureCapacity(int minimumCapacity)
4将字符从当前序列复制到目标字符数组void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
5返回第一次出现指定子字符串的索引int indexOf(String str)
6返回指定位置开始,第一次出现指定子字符串的索引int indexOf(String str, int fromIndex)
7返回最后一次出现指定子字符串的索引int lastIndexOf(String str)
8返回子字符串最后一次出现的索引int lastIndexOf(String str, int fromIndex)
9返回字符串的长度(字符数)int length()
10设置指定位置的字符void setCharAt(int index, char ch)
11设置字符序列的长度void setLength(int newLength)
12返回此序列的子序列CharSequence subSequence(int start, int end)
13返回当前字符序列的子字符串String substring(int start)
14返回指定范围内的子字符串String substring(int start, int end)
15返回字符序列的字符串表示形式String toString()