Java.lang包完整指南:从Object到String的全面解析
本文全面解析Java语言核心包java.lang,详细介绍了Object、String、StringBuilder、包装类、Math、System和Throwable等基础类的使用方法。每个类都配有完整的代码示例,涵盖对象比较、字符串操作、数学运算、系统功能调用和异常处理等实际应用场景,帮助Java开发者深入理解并熟练运用这些基础类库。
java.lang 是 Java 语言的核心包,包含了许多基础类和接口,这些类在 Java 程序运行过程中起着至关重要的作用。该包会被 Java 编译器自动导入,无需显式使用 import 语句。
主要类和接口
1、Object 类
所有 Java 类的根类,提供基本方法:
1、equals():对象相等性比较
2、hashCode():返回对象的哈希码
3、toString():返回对象的字符串表示
4、getClass():获取对象的运行时类
public class ObjectExample {
public static void main(String[] args) {
Person p1 = new Person("Alice", 25);
Person p2 = new Person("Alice", 25);
System.out.println(p1.toString()); // 输出: Person{name='Alice', age=25}
System.out.println(p1.equals(p2)); // 输出: true
System.out.println(p1.getClass().getName()); // 输出: Person
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}2. String 类
不可变字符序列,提供了丰富的字符串操作方法。
public class StringExample {
public static void main(String[] args) {
// 字符串创建
String str1 = "Hello";
String str2 = new String("World");
// 常用方法
System.out.println("Length: " + str1.length()); // 5
System.out.println("Uppercase: " + str1.toUpperCase()); // HELLO
System.out.println("Substring: " + str1.substring(1, 4)); // ell
System.out.println("Contains 'ell': " + str1.contains("ell")); // true
System.out.println("Equals: " + str1.equals("hello")); // false
System.out.println("Equals ignore case: " + str1.equalsIgnoreCase("hello")); // true
// 字符串连接
String result = str1.concat(" ").concat(str2);
System.out.println("Concatenated: " + result); // Hello World
// 字符串分割
String csv = "Java,Python,JavaScript,C++";
String[] languages = csv.split(",");
for (String lang : languages) {
System.out.println(lang);
}
// 字符串格式化
String formatted = String.format("Name: %s, Age: %d", "John", 30);
System.out.println(formatted);
}
}3. StringBuilder 和 StringBuffer
可变的字符序列,适用于频繁修改字符串的场景。
public class StringBuilderExample {
public static void main(String[] args) {
// StringBuilder (非线程安全,性能更好)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.insert(5, ",");
System.out.println(sb.toString()); // Hello, World
// StringBuffer (线程安全)
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Java");
stringBuffer.append(" ");
stringBuffer.append("Programming");
System.out.println(stringBuffer.toString()); // Java Programming
// 性能对比
long startTime = System.currentTimeMillis();
StringBuilder performanceTest = new StringBuilder();
for (int i = 0; i < 100000; i++) {
performanceTest.append(i);
}
long endTime = System.currentTimeMillis();
System.out.println("StringBuilder time: " + (endTime - startTime) + "ms");
}
}4. 包装类
基本数据类型的对象表示。
public class WrapperClassExample {
public static void main(String[] args) {
// 自动装箱和拆箱
Integer integerObj = 100; // 自动装箱
int primitiveInt = integerObj; // 自动拆箱
// 常用方法
System.out.println("Integer max value: " + Integer.MAX_VALUE);
System.out.println("Integer min value: " + Integer.MIN_VALUE);
// 字符串转换
String numberStr = "123";
int number = Integer.parseInt(numberStr);
System.out.println("Parsed number: " + number);
// 比较
Integer a = 100;
Integer b = 200;
System.out.println("Compare: " + a.compareTo(b)); // -1 (a < b)
// 其他包装类示例
Double doubleObj = 3.14;
Boolean booleanObj = true;
Character charObj = 'A';
System.out.println("Double value: " + doubleObj.doubleValue());
System.out.println("Boolean value: " + booleanObj.booleanValue());
System.out.println("Character: " + charObj.charValue());
}
}5. Math 类
提供数学运算的静态方法。
public class MathExample {
public static void main(String[] args) {
// 基本运算
System.out.println("Absolute: " + Math.abs(-10)); // 10
System.out.println("Max: " + Math.max(5, 10)); // 10
System.out.println("Min: " + Math.min(5, 10)); // 5
System.out.println("Power: " + Math.pow(2, 3)); // 8.0
// 三角函数
System.out.println("Sin 90: " + Math.sin(Math.PI / 2)); // 1.0
System.out.println("Cos 0: " + Math.cos(0)); // 1.0
// 对数运算
System.out.println("Log 10: " + Math.log10(100)); // 2.0
System.out.println("Natural log: " + Math.log(Math.E)); // 1.0
// 随机数
System.out.println("Random: " + Math.random()); // 0.0 ~ 1.0 之间的随机数
// 四舍五入
System.out.println("Round: " + Math.round(3.6)); // 4
System.out.println("Ceil: " + Math.ceil(3.2)); // 4.0
System.out.println("Floor: " + Math.floor(3.8)); // 3.0
// 平方根
System.out.println("Square root: " + Math.sqrt(16)); // 4.0
}
}6. System 类
提供系统相关的功能。
public class SystemExample {
public static void main(String[] args) {
// 标准输出
System.out.println("This is standard output");
System.err.println("This is error output");
// 获取系统属性
System.out.println("Java version: " + System.getProperty("java.version"));
System.out.println("OS name: " + System.getProperty("os.name"));
System.out.println("User home: " + System.getProperty("user.home"));
// 获取当前时间
long startTime = System.currentTimeMillis();
long nanoTime = System.nanoTime();
// 执行垃圾回收
System.gc();
// 数组复制
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
System.arraycopy(source, 0, destination, 0, source.length);
System.out.println("Copied array: " + Arrays.toString(destination));
// 退出程序
// System.exit(0); // 正常退出
}
}7. Throwable 类
所有错误和异常的基类。
public class ExceptionExample {
public static void main(String[] args) {
try {
// 可能抛出异常的代码
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// 异常处理
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
// 无论是否发生异常都会执行
System.out.println("This is finally block");
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
}总结
java.lang 包包含了 Java 编程中最基础和重要的类:
1、Object:所有类的根类
2、String:不可变字符串处理
3、StringBuilder/StringBuffer:可变字符串处理
4、包装类:基本类型的对象表示
5、Math:数学运算工具
6、System:系统相关功能
7、Throwable:异常处理基础
这些类为 Java 程序提供了最基本的功能支持,是每个 Java 开发者必须熟练掌握的核心内容。
最后更新于4月前
本文由人工编写,AI优化,转载请注明原文地址: Java.lang包详解:核心类使用方法与实战代码示例
推荐阅读
评论 (1)
发表评论
昵称:加载中...
艾米丽2025-11-10 18:53:09
感谢作者分享!之前一直对equals和hashCode的关联不太清楚,文中的Person类示例让我彻底明白了如何正确重写这两个方法,正好用在了我现在的用户管理系统里。