好的!以下是对 Java 基础知识的更多代码示例,涵盖不同场景和用法:
---
### **一、基本语法扩展**
#### 1. **类型转换**
```java
// 自动类型转换(小转大)
int a = 10;
double b = a; // int → double
// 强制类型转换(大转小)
double c = 20.5;
int d = (int) c; // 输出 20(精度丢失)
// 字符串转数值
String str = "123";
int num = Integer.parseInt(str); // 转为 int
```
#### 2. **运算符优先级**
```java
int result = 5 + 3 * 2; // 3*2=6 → 5+6=11
System.out.println(result); // 11
// 括号改变优先级
int result2 = (5 + 3) * 2; // 8*2=16
```
---
### **二、控制流扩展**
#### 1. **嵌套循环(打印九九乘法表)**
```java
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "×" + i + "=" + (i * j) + "\t");
}
System.out.println();
}
```
#### 2. **增强 for 循环(遍历数组)**
```java
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.print(num + " "); // 输出 1 2 3 4 5
}
```
---
### **三、面向对象扩展**
#### 1. **多态的实际应用**
```java
class Animal {
void sound() {
System.out.println("动物发出声音");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("喵喵");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("汪汪");
}
}
// 使用多态
Animal animal1 = new Cat();
Animal animal2 = new Dog();
animal1.sound(); // 喵喵
animal2.sound(); // 汪汪
```
#### 2. **静态变量与方法**
```java
class Counter {
static int count = 0; // 静态变量,属于类
Counter() {
count++; // 每次创建对象时计数
}
static void printCount() { // 静态方法
System.out.println("对象数量:" + count);
}
}
// 测试
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter.printCount(); // 输出 2
```
---
### **四、异常处理扩展**
#### 1. **自定义异常**
```java
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
// 使用自定义异常
try {
throw new MyException("自定义异常示例");
} catch (MyException e) {
System.out.println("捕获异常:" + e.getMessage());
}
```
#### 2. **多重 catch 块**
```java
try {
int[] arr = new int[3];
arr[5] = 10; // 抛出 ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("算术异常");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常"); // 执行这里
} catch (Exception e) {
System.out.println("通用异常");
}
```
---
### **五、集合框架扩展**
#### 1. **LinkedList 与 ArrayList 对比**
```java
List<String> arrayList = new ArrayList<>(); // 基于数组,适合随机访问
arrayList.add("A");
arrayList.add("B");
List<String> linkedList = new LinkedList<>(); // 基于链表,适合频繁插入/删除
linkedList.add("X");
linkedList.add(0, "Y"); // 在头部插入
```
#### 2. **遍历 Map**
```java
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
// 遍历键值对
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 使用 Lambda 遍历(Java 8+)
scores.forEach((k, v) -> System.out.println(k + " -> " + v));
```
---
### **六、输入输出扩展**
#### 1. **写入文件**
```java
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Hello, Java!");
writer.newLine();
writer.write("第二行内容");
} catch (IOException e) {
e.printStackTrace();
}
```
#### 2. **序列化与反序列化对象**
```java
// 需要实现 Serializable 接口
class Student implements Serializable {
String name;
int age;
}
// 序列化对象到文件
Student stu = new Student();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.dat"))) {
oos.writeObject(stu);
}
// 从文件反序列化对象
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.dat"))) {
Student stu2 = (Student) ois.readObject();
}
```
---
### **七、多线程扩展**
#### 1. **线程同步(synchronized 方法)**
```java
class Counter {
private int count = 0;
public synchronized void increment() { // 同步方法
count++;
}
public int getCount() {
return count;
}
}
// 测试线程安全
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.getCount()); // 输出 2000
```
#### 2. **使用 Callable 和 Future**
```java
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
// 获取异步结果
int result = future.get(); // 阻塞直到任务完成
System.out.println("结果:" + result); // 输出 42
executor.shutdown();
```
---
### **八、常用类库扩展**
#### 1. **StringBuilder 高效操作字符串**
```java
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("Java");
sb.insert(5, ","); // Hello, Java
sb.reverse(); // avaJ ,olleH
System.out.println(sb.toString());
```
#### 2. **日期时间 API(Java 8+)**
```java
LocalDate today = LocalDate.now(); // 当前日期
LocalDate nextWeek = today.plusWeeks(1); // 加一周
LocalDateTime now = LocalDateTime.now(); // 当前日期时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter); // 格式化输出
```
---
### **九、JDK 新特性扩展**
#### 1. **方法引用(Method Reference)**
```java
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// 替换 Lambda 为方法引用
names.forEach(System.out::println);
```
#### 2. **Optional 避免空指针**
```java
Optional<String> name = Optional.ofNullable(getName()); // getName() 可能返回 null
String result = name.orElse("默认值"); // 如果 name 为空,返回 "默认值"
// 链式操作
name.ifPresent(n -> System.out.println(n.length()));
```
---
### **十、综合案例:简易计算器**
```java
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("输入第一个数字:");
double num1 = scanner.nextDouble();
System.out.print("输入运算符(+、-、*、/):");
char operator = scanner.next().charAt(0);
System.out.print("输入第二个数字:");
double num2 = scanner.nextDouble();
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
throw new ArithmeticException("除数不能为0");
}
result = num1 / num2;
break;
default:
throw new IllegalArgumentException("无效运算符");
}
System.out.println("结果:" + result);
}
}
```
---
以上示例覆盖了 Java 基础的不同方面,可以通过实际运行这些代码来加深理解。如果有具体问题或需要更深入的解释,欢迎随时提问!







网友评论