Java核心语法:从变量到控制流
一、变量与数据类型(对比Python/C++特性)
1. 变量声明三要素
// Java(强类型语言,需显式声明类型)
int age = 25;
String name = "CSDN"; // Python(动态类型)
age = 25
name = "CSDN" // C++(类似Java,但需分号结尾)
int age = 25;
std::string name = "CSDN";
2. Java八大基本数据类型
类型 | 关键字 | 取值范围 | 内存占用 |
---|---|---|---|
整型 | int | -2^31 ~ 2^31-1 | 4字节 |
长整型 | long | -2^63 ~ 2^63-1 | 8字节 |
双精度浮点 | double | ±4.9e-324 ~ ±1.8e+308 | 8字节 |
布尔 | boolean | true/false | 1字节 |
❗ 避坑指南:
- 浮点数比较不要用
==
(用差值绝对值< 1e-6
) long
类型赋值需加L
后缀:long num = 10000000000L;
二、运算符与表达式
1. 算术运算符的特殊行为
int a = 10 / 3; // 结果3(整数除法)
double b = 10 / 3.0; // 结果3.333... int c = 10 % 3; // 结果1(取模)
2. 比较运算符 vs 逻辑运算符
类型 | 运算符 | 示例 |
---|---|---|
比较 | > < >= <= == | if (age >= 18) |
逻辑 | && \|\| ! | if (score > 60 && !cheating) |
❗ 短路特性:
false && ...
不会执行右侧true || ...
不会执行右侧
三、控制流:条件与循环
1. 条件语句(对比Python缩进 vs Java大括号)
Java写法:
if (score >= 90) { System.out.println("A");
} else if (score >= 60) { System.out.println("B");
} else { System.out.println("C");
}
Python写法:
if score >= 90: print("A")
elif score >= 60: print("B")
else: print("C")
2. switch-case(JDK12+箭头表达式)
String day = "Monday";
switch (day) { case "Monday" -> System.out.println("工作日"); case "Saturday", "Sunday" -> System.out.println("休息日"); default -> System.out.println("无效输入");
}
3. 循环结构
for循环:
// 打印1-10(对比C++的相似性)
for (int i = 1; i <= 10; i++) { System.out.println(i);
}
while循环:
int count = 0;
while (count < 5) { System.out.println("执行第" + (count+1) + "次"); count++; // 必须更新循环变量!
}
增强for循环:
int[] nums = {1, 2, 3};
for (int num : nums) { System.out.println(num);
}
四、综合实战:简易计算器
import java.util.Scanner; 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(); switch (operator) { case '+' -> System.out.println("结果:" + (num1 + num2)); case '-' -> System.out.println("结果:" + (num1 - num2)); case '*' -> System.out.println("结果:" + (num1 * num2)); case '/' -> { if (num2 == 0) System.out.println("错误:除数不能为0!"); else System.out.println("结果:" + (num1 / num2)); } default -> System.out.println("无效运算符"); } }
}
五、常见错误与调试技巧
-
编译错误:找不到符号
- 检查变量名拼写和作用域(局部变量不能在外部使用)
-
逻辑错误:循环不执行
int i = 10; while (i < 5) { // 条件永远不满足 // 代码不会执行 }
-
空指针异常(NPE)预判
String str = null; if (str != null && !str.isEmpty()) { // 利用短路特性避免NPE System.out.println(str.length()); }