一份用于日常开发的 Java 核心语法速查表,涵盖基础语法、面向对象、集合框架、异常处理、IO 流等常用场景。
一、Hello World
java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
编译运行:
java
javac HelloWorld.java # 编译
java HelloWorld # 运行
二、基本语法
2.1 变量与数据类型
基本数据类型(8种):
| 类型 | 关键字 | 大小 | 取值范围 |
|---|---|---|---|
| 字节型 | byte |
1字节 | -128 ~ 127 |
| 短整型 | short |
2字节 | -32768 ~ 32767 |
| 整型 | int |
4字节 | -21亿 ~ 21亿 |
| 长整型 | long |
8字节 | 需加 L 后缀 |
| 单精度浮点 | float |
4字节 | 需加 F 后缀 |
| 双精度浮点 | double |
8字节 | 默认小数类型 |
| 字符型 | char |
2字节 | 单引号包裹 |
| 布尔型 | boolean |
1位 | true / false |
java
int age = 25;
double price = 99.9;
long bigNum = 10000000000L;
float f = 3.14F;
char grade = 'A';
boolean isActive = true;
引用数据类型:
java
String name = "Java";
int[] arr = {1, 2, 3};
Object obj = new Object();
2.2 变量类型转换
java
// 自动类型转换(小→大)
int a = 10;
double b = a; // 10.0
// 强制类型转换(大→小,可能丢失精度)
double d = 9.99;
int i = (int) d; // 9
// 字符串转数字
int num = Integer.parseInt("123");
double dnum = Double.parseDouble("3.14");
// 数字转字符串
String str = String.valueOf(123);
2.3 运算符
| 类别 | 运算符 |
|---|---|
| 算术 | + - * / % ++ -- |
| 赋值 | = += -= *= /= %= |
| 比较 | == != > < >= <= |
| 逻辑 | && 或 且 |
| 位运算 | & 且 ^ ~ << >> >>> |
| 三元 | 条件 ? 值1 : 值2 |
java
int result = (a > b) ? a : b; // 取较大值
三、控制流程
3.1 条件语句
java
// if-else
if (score >= 90) {
System.out.println("A");
} else if (score >= 60) {
System.out.println("B");
} else {
System.out.println("C");
}
// switch
switch (day) {
case 1: System.out.println("周一"); break;
case 2: System.out.println("周二"); break;
default: System.out.println("未知");
}
3.2 循环语句
java
// for 循环
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
// 增强 for-each
int[] nums = {1, 2, 3, 4, 5};
for (int num : nums) {
System.out.println(num);
}
// while 循环
while (i < 10) {
System.out.println(i);
i++;
}
// do-while
do {
System.out.println(i);
i++;
} while (i < 10);
四、面向对象(OOP)
4.1 类与对象
java
// 定义类
public class Person {
// 属性(成员变量)
private String name;
private int age;
// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 无参构造
public Person() {}
// 方法
public void sayHello() {
System.out.println("Hello, " + name);
}
// Getter / Setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
// 使用
Person p = new Person("张三", 18);
p.sayHello();
4.2 三大特性
封装:
java
// 使用 private 修饰属性,通过 public 方法访问
private String name;
public String getName() { return name; }
继承:
java
// 子类继承父类,使用 extends
public class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age); // 调用父类构造
this.school = school;
}
@Override // 重写父类方法
public void sayHello() {
System.out.println("我是学生 " + getName());
}
}
多态:
java
Person p = new Student("李四", 20, "清华大学");
p.sayHello(); // 调用的是 Student 的重写方法
4.3 访问修饰符
| 修饰符 | 同类 | 同包 | 子类 | 任何类 |
|---|---|---|---|---|
private |
✅ | ❌ | ❌ | ❌ |
default(不写) |
✅ | ✅ | ❌ | ❌ |
protected |
✅ | ✅ | ✅ | ❌ |
public |
✅ | ✅ | ✅ | ✅ |
4.4 抽象类与接口
java
// 抽象类(不能实例化)
public abstract class Animal {
public abstract void makeSound(); // 抽象方法
public void sleep() {
System.out.println("睡觉中...");
}
}
// 接口(所有方法默认 public abstract)
public interface Flyable {
void fly(); // 自动 public abstract
default void glide() { // 默认方法(JDK 8+)
System.out.println("滑翔中...");
}
}
// 实现类
public class Bird extends Animal implements Flyable {
@Override
public void makeSound() {
System.out.println("叽叽喳喳");
}
@Override
public void fly() {
System.out.println("飞起来了");
}
}
4.5 static 和 final
java
// static:属于类,不属于对象
public class Counter {
public static int count = 0; // 静态变量
public static void showCount() { // 静态方法
System.out.println(count);
}
}
// 使用:Counter.showCount(); 或 Counter.count;
// final:不可变
final double PI = 3.14159; // 常量
final class MyClass {} // 不能被继承
public final void method() {} // 不能被重写
五、数组
java
// 声明和初始化
int[] arr1 = new int[5];
int[] arr2 = {1, 2, 3, 4, 5};
int[] arr3 = new int[]{1, 2, 3};
// 遍历
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]);
}
for (int num : arr2) {
System.out.println(num);
}
// 多维数组
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
int value = matrix[1][2]; // 6
六、字符串
java
// 创建
String s1 = "Hello";
String s2 = new String("Hello");
// 常用方法
String str = "Java Programming";
str.length(); // 长度
str.charAt(0); // 'J'
str.substring(0, 4); // "Java"
str.indexOf("Pro"); // 5
str.toLowerCase(); // "java programming"
str.toUpperCase(); // "JAVA PROGRAMMING"
str.replace("Java", "Python");
str.split(" "); // ["Java", "Programming"]
str.trim(); // 去掉首尾空格
str.startsWith("Java"); // true
str.endsWith("ing"); // true
// 字符串比较
String a = "hello";
String b = "hello";
a.equals(b); // true(比较内容)
a == b; // 可能 true 也可能 false(比较引用)
"abc".compareTo("abd"); // -1(字典序比较)
// StringBuilder(可变字符串,高效)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString(); // "Hello World"
七、集合框架(Collection)
7.1 List(有序,可重复)
java
// ArrayList(最常用,底层数组)
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add(1, "Orange"); // 插入
list.get(0); // "Apple"
list.remove("Apple");
list.size();
// LinkedList(链表)
List<String> list2 = new LinkedList<>();
// 遍历
for (String item : list) {
System.out.println(item);
}
7.2 Set(无序,不可重复)
java
// HashSet(最常用)
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // 重复,不会添加
// TreeSet(自动排序)
Set<Integer> sortedSet = new TreeSet<>();
sortedSet.add(5);
sortedSet.add(2);
sortedSet.add(8); // [2, 5, 8]
7.3 Map(键值对)
java
// HashMap(最常用)
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.get("Apple"); // 10
map.getOrDefault("Orange", 0); // 0
map.containsKey("Apple"); // true
map.keySet(); // 所有键
map.values(); // 所有值
// 遍历 Map
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
八、异常处理
java
// try-catch
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("除数不能为0:" + e.getMessage());
} finally {
System.out.println("无论如何都会执行");
}
// throws(声明抛出异常)
public void readFile() throws IOException {
// 可能抛出 IOException 的代码
}
// 自定义异常
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
九、IO 流
9.1 文件读写
java
// 写入文件
try (FileWriter writer = new FileWriter("output.txt")) {
writer.write("Hello Java");
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
9.2 控制台输入
java
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("请输入姓名:");
String name = scanner.nextLine();
System.out.print("请输入年龄:");
int age = scanner.nextInt();
scanner.close();
十、常用工具类
java
// 日期时间(Java 8+)
import java.time.*;
LocalDate date = LocalDate.now();
LocalDateTime datetime = LocalDateTime.now();
LocalDate.parse("2024-01-01");
date.plusDays(7);
date.getYear(); // 2024
date.getMonthValue(); // 1
// Math
Math.max(10, 20); // 20
Math.min(10, 20); // 10
Math.sqrt(16); // 4.0
Math.random(); // 0.0 ~ 1.0 随机数
// Arrays
int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr);
Arrays.toString(arr); // [1, 1, 3, 4, 5]
十一、快速检查清单
| 场景 | 用什么 |
|---|---|
| 存储多个数据 | ArrayList / 数组 |
| 存储不重复数据 | HashSet |
| 存储键值对 | HashMap |
| 线程安全 | ConcurrentHashMap / Vector |
| 字符串拼接(大量) | StringBuilder |
| 文件读写 | FileWriter / BufferedReader |
| 日期时间 | LocalDateTime |
| 异常处理 | try-catch-finally |
十二、常用命令
java
# 编译
javac Hello.java
# 运行
java Hello
# 查看 Java 版本
java -version
# 打包成 JAR
jar -cf myapp.jar *.class
# 运行 JAR
java -jar myapp.jar