Java 基础全面解析
一、Java 简介与开发环境
1.1 Java 是什么?
Java 是一种跨平台、面向对象的编程语言,由 Sun Microsystems 于 1995 年发布。其核心特点是“一次编写,到处运行”(Write Once, Run Anywhere),通过 JVM 实现跨平台。
核心特性:
- 简单易学:语法类似 C++,但去除复杂特性(如指针)
- 面向对象:以类和对象为基础组织代码
- 自动内存管理:垃圾回收机制自动释放内存
- 丰富的类库:提供集合、IO、网络等工具包
1.2 开发环境搭建
- 安装 JDK:从 Oracle官网 下载并安装
- 配置环境变量:
JAVA_HOME
:指向 JDK 安装路径(如C:\Program Files\Java\jdk-17
)Path
:添加%JAVA_HOME%\bin
- 验证安装:
-
java -version
二、基础语法
2.1 第一个 Java 程序
public class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World!");}
}
public class HelloWorld
:类名必须与文件名一致public static void main(String[] args)
:程序入口方法System.out.println
:输出文本到控制台
运行步骤:
- 保存为
HelloWorld.java
- 编译:
javac HelloWorld.java
- 运行:
java HelloWorld
2.2 变量与数据类型
基本数据类型:
类型 | 大小 | 默认值 | 示例 |
---|---|---|---|
byte | 1字节 | 0 | byte b = 10; |
int | 4字节 | 0 | int age = 25; |
double | 8字节 | 0.0 | double pi = 3.14; |
boolean | 1位 | false | boolean isJavaFun = true; |
char | 2字节 | '\u0000' | char grade = 'A'; |
引用数据类型:
- 类:如
String
- 数组:如
int[] numbers = {1, 2, 3};
变量声明示例:
String name = "Alice"; // 字符串
int[] scores = {90, 85, 77}; // 数组
2.3 运算符
类型 | 运算符 | 示例 |
---|---|---|
算术运算符 | + , - , * , / , % | int sum = 5 + 3; |
比较运算符 | == , != , > , < | boolean isEqual = (a == b); |
逻辑运算符 | && , ` | |
赋值运算符 | = , += , -= | x += 5; // x = x + 5 |
三、控制结构
3.1 条件语句
if-else 示例:
int score = 85;
if (score >= 90) {System.out.println("优秀");
} else if (score >= 60) {System.out.println("及格");
} else {System.out.println("不及格");
}
switch 示例:
int day = 3;
switch (day) {case 1: System.out.println("周一"); break;case 2: System.out.println("周二"); break;default: System.out.println("其他");
}
3.2 循环结构
for 循环:
for (int i = 0; i < 5; i++) {System.out.println("当前值: " + i);
}
while 循环:
int count = 0;
while (count < 3) {System.out.println("Count: " + count);count++;
}
增强 for 循环:
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {System.out.println(fruit);
}
四、面向对象编程(OOP)
4.1 类与对象
类定义:
public class Dog {// 属性String breed;int age;// 方法void bark() {System.out.println("汪汪!");}
}
创建对象:
Dog myDog = new Dog();
myDog.breed = "金毛";
myDog.age = 3;
myDog.bark();
4.2 构造方法
public class Book {String title;String author;// 构造方法public Book(String t, String a) {title = t;author = a;}
}// 使用构造方法创建对象
Book book = new Book("Java编程思想", "Bruce Eckel");
4.3 继承
父类:
public class Animal {void eat() {System.out.println("动物在吃东西");}
}
子类:
public class Cat extends Animal {void meow() {System.out.println("喵喵叫");}
}// 使用继承
Cat myCat = new Cat();
myCat.eat(); // 继承自Animal
myCat.meow();
4.4 多态
接口定义:
interface Shape {double calculateArea();
}
实现类:
class Circle implements Shape {double radius;Circle(double r) { radius = r; }@Overridepublic double calculateArea() {return Math.PI * radius * radius;}
}class Square implements Shape {double side;Square(double s) { side = s; }@Overridepublic double calculateArea() {return side * side;}
}
使用多态
Shape shape1 = new Circle(5.0);
Shape shape2 = new Square(4.0);
System.out.println("圆面积: " + shape1.calculateArea());
System.out.println("正方形面积: " + shape2.calculateArea());
五、异常处理
5.1 try-catch 块
try {int[] numbers = {1, 2, 3};System.out.println(numbers[5]); // 抛出ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {System.out.println("数组越界错误: " + e.getMessage());
} finally {System.out.println("无论是否异常都会执行");
}
5.2 自定义异常
class InsufficientFundsException extends Exception {InsufficientFundsException(String message) {super(message);}
}class BankAccount {double balance;void withdraw(double amount) throws InsufficientFundsException {if (amount > balance) {throw new InsufficientFundsException("余额不足");}balance -= amount;}
}
六、集合框架
6.1 List 示例
import java.util.ArrayList;
import java.util.List;List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.remove(0);
System.out.println(fruits.get(0)); // 输出 Banana
6.2 Map 示例
import java.util.HashMap;
import java.util.Map;Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
System.out.println(scores.get("Alice")); // 输出 90
七、输入输出(IO)
7.1 文件读写
import java.io.*;// 写入文件
try (FileWriter writer = new FileWriter("data.txt")) {writer.write("Hello, Java IO!");
}// 读取文件
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {String line = reader.readLine();System.out.println(line); // 输出 Hello, Java IO!
}
八、多线程
8.1 继承 Thread 类
class MyThread extends Thread {public void run() {for (int i = 0; i < 3; i++) {System.out.println("线程运行中: " + i);}}
}public class Main {public static void main(String[] args) {MyThread t1 = new MyThread();t1.start(); // 启动线程}
}
8.2 实现 Runnable 接口
class MyRunnable implements Runnable {public void run() {System.out.println("通过Runnable实现线程");}
}public class Main {public static void main(String[] args) {Thread t2 = new Thread(new MyRunnable());t2.start();}
}
九、Java 新特性
9.1 Lambda 表达式
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name)); // 遍历输出每个名字
9.2 Stream API
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().filter(n -> n % 2 == 0).mapToInt(n -> n).sum();
System.out.println(sum); // 输出 6 (2+4)
十、总结
通过以上内容,掌握 Java 的核心语法、面向对象编程、异常处理、集合框架等基础知识.