200字引言:
第一次接触Java是在大学二年级的编程课上,当时被它"一次编写,到处运行"的特性深深吸引。作为一门诞生于1995年的编程语言,Java至今仍保持着惊人的生命力——根据2023年TIOBE指数显示,Java长期稳居全球编程语言排行榜前三甲。这主要得益于其强大的跨平台能力、丰富的类库生态以及在企业级开发中的统治地位。从Android应用到大型分布式系统,从金融交易平台到大数据处理框架,Java的身影无处不在。
学习Java语法就像掌握乐理基础,虽然初期可能会觉得枯燥,但这是后续编写复杂程序的基石。我在教学过程中发现,很多同学在面向对象概念、异常处理等核心语法环节容易形成知识漏洞,而这些恰恰是面试中最常考察的重点。本文将用工程实践中的真实案例,带你系统掌握Java基础语法的关键要点。
推荐使用Oracle JDK 17 LTS版本(当前长期支持版),安装时需注意:
java -version应显示版本信息注意:企业环境中常会遇到多JDK版本共存问题,可通过JEnv或手动修改环境变量切换版本
IntelliJ IDEA社区版(免费)是当前Java开发的事实标准,相比Eclipse:
首次使用建议调整两个设置:
java复制public class HelloWorld { // 类名必须与文件名一致(区分大小写)
public static void main(String[] args) { // JVM入口方法
System.out.println("Hello, Java!"); // 标准输出
}
}
编译运行流程:
javac HelloWorld.java生成.class字节码java HelloWorld(注意不要加.class后缀)Java是强类型语言,所有变量必须先声明后使用。基本数据类型包括:
| 类型 | 大小 | 取值范围 | 默认值 |
|---|---|---|---|
| byte | 8-bit | -128 ~ 127 | 0 |
| short | 16-bit | -32768 ~ 32767 | 0 |
| int | 32-bit | -2^31 ~ (2^31-1) | 0 |
| long | 64-bit | -2^63 ~ (2^63-1) | 0L |
| float | 32-bit | IEEE 754 | 0.0f |
| double | 64-bit | IEEE 754 | 0.0d |
| char | 16-bit | Unicode字符 | '\u0000' |
| boolean | 1-bit | true/false | false |
类型转换注意事项:
double d = 3.14; int i = (int)d; // i=3易错点:
5 / 2 = 2(不是2.5)&&和||会提前终止判断result = (a > b) ? a : b;<<左移相当于乘2,>>右移相当于除2java复制// if-else if阶梯
if(score >= 90) {
grade = 'A';
} else if(score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
// switch增强(Java 12+)
String dayType = switch(day) {
case "Mon", "Tue", "Wed", "Thu", "Fri" -> "Weekday";
case "Sat", "Sun" -> "Weekend";
default -> throw new IllegalArgumentException();
};
// 循环控制
for(int i=0; i<10; i++) {
if(i == 5) break;
System.out.println(i);
}
// 带标签的break
outer: for(int i=0; i<5; i++) {
for(int j=0; j<5; j++) {
if(i*j > 6) break outer;
}
}
java复制public class Person {
// 字段(成员变量)
private String name; // 封装:private保护数据
private int age;
// 构造方法
public Person(String name, int age) {
this.name = name; // this解决命名冲突
this.age = age;
}
// 方法
public void introduce() {
System.out.println("I'm " + name + ", " + age + " years old.");
}
// Getter/Setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
java复制class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age); // 调用父类构造
this.school = school;
}
@Override // 方法重写
public void introduce() {
super.introduce();
System.out.println("I study at " + school);
}
}
设计原则:优先使用组合而非继承,继承要满足is-a关系
java复制interface Drawable {
void draw(); // 默认public abstract
default void resize() { // Java8默认方法
System.out.println("Resizing...");
}
}
abstract class Shape implements Drawable {
protected String color;
public abstract double area();
}
class Circle extends Shape {
private double radius;
@Override
public void draw() {
System.out.println("Drawing a " + color + " circle");
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
code复制Throwable
├── Error(系统错误,如OutOfMemoryError)
└── Exception
├── RuntimeException(未检异常)
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ └── ...
└── 非RuntimeException(已检异常)
├── IOException
├── SQLException
└── ...
java复制try {
FileInputStream fis = new FileInputStream("test.txt");
int data = fis.read();
} catch (FileNotFoundException e) {
System.err.println("文件未找到: " + e.getMessage());
} catch (IOException e) {
System.err.println("IO错误: " + e.getStackTrace());
} finally {
if(fis != null) {
try { fis.close(); }
catch (IOException e) { /* 忽略关闭异常 */ }
}
}
java复制class InsufficientFundsException extends Exception {
private double shortage;
public InsufficientFundsException(double shortage) {
super("资金不足,还差" + shortage);
this.shortage = shortage;
}
public double getShortage() { return shortage; }
}
class BankAccount {
public void withdraw(double amount) throws InsufficientFundsException {
if(balance < amount) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
}
code复制Collection
├── List(有序可重复)
│ ├── ArrayList(数组实现,随机访问快)
│ └── LinkedList(链表实现,插入删除快)
├── Set(无序唯一)
│ ├── HashSet(哈希表实现)
│ └── TreeSet(红黑树实现,有序)
└── Queue(队列)
└── Deque(双端队列)
Map(键值对)
├── HashMap(哈希表实现)
└── TreeMap(红黑树实现,按键排序)
java复制List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add(1, "C++"); // 插入到指定位置
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 90);
map.put("Bob", 85);
int score = map.get("Alice"); // 90
// Java8 Stream操作
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(n -> n * 2)
.sum();
Collections.synchronizedList()而非Vectorcode复制字节流(8位)
├── InputStream
│ ├── FileInputStream
│ └── BufferedInputStream
└── OutputStream
├── FileOutputStream
└── BufferedOutputStream
字符流(16位Unicode)
├── Reader
│ ├── FileReader
│ └── BufferedReader
└── Writer
├── FileWriter
└── BufferedWriter
java复制// 使用try-with-resources自动关闭资源
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line.toUpperCase());
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
java复制Path path = Paths.get("data.txt");
try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
Files.write(Paths.get("copy.txt"), lines);
} catch (IOException e) {
System.err.println("文件操作失败: " + e);
}
java复制// 方式1:继承Thread类
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
// 方式2:实现Runnable接口
class MyTask implements Runnable {
public void run() {
System.out.println("Task running");
}
}
// 启动线程
new MyThread().start();
new Thread(new MyTask()).start();
// Java8 Lambda简化
new Thread(() -> System.out.println("Lambda thread")).start();
java复制class Counter {
private int count = 0;
private final Object lock = new Object();
public void increment() {
synchronized(lock) { // 同步代码块
count++;
}
}
public synchronized int getCount() { // 同步方法
return count;
}
}
java复制ExecutorService executor = Executors.newFixedThreadPool(4);
for(int i=0; i<10; i++) {
executor.submit(() -> {
System.out.println(Thread.currentThread().getName() + " executing");
});
}
executor.shutdown();
java复制List<String> names = Arrays.asList("Alice", "Bob");
names.sort((a, b) -> a.compareTo(b));
java复制List<Integer> squares = IntStream.range(1, 10)
.map(n -> n * n)
.boxed()
.collect(Collectors.toList());
java复制Optional<String> name = Optional.ofNullable(getName());
String result = name.orElse("default");
java复制var list = new ArrayList<String>(); // 自动推断为ArrayList<String>
java复制String multiline = """
This is a
multiline
string""";
java复制HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
使用IDE调试器:
日志记录:
java复制import java.util.logging.*;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class.getName());
public static void main(String[] args) {
logger.info("程序启动");
try {
// 业务代码
} catch (Exception e) {
logger.log(Level.SEVERE, "发生错误", e);
}
}
}
常用启动参数:
-Xms512m 初始堆大小-Xmx1024m 最大堆大小-XX:+HeapDumpOnOutOfMemoryError OOM时生成堆转储-XX:+PrintGCDetails 打印GC日志new ArrayList<>(100))java复制// 读取文件时指定编码
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream("data.txt"), "UTF-8"));
java复制// 使用java.time包(Java8+)
LocalDate today = LocalDate.now();
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String formatted = now.format(formatter);
使用try-with-resources确保资源关闭:
java复制try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
// 处理结果集
} // 自动调用close()
在多年的Java开发中,我发现很多初学者容易陷入"过度学习语法细节"的误区。实际上,企业更看重的是用Java解决实际问题的能力。建议在学习基础语法后,尽快开始小项目实践,遇到问题再针对性查漏补缺。记住,编程语言只是工具,解决问题的思维才是核心。