欢迎光临
我们一直在努力

Python转Java系列:语法与类型系统

文章目录

  • 第 2 章:语法与类型系统
    • Python 对照表
    • 2.1 基本类型
    • 2.2 类型转换
    • 2.3 字符串
    • 2.4 数组 vs 列表
    • 2.5 `var` 局部类型推断(Java 10+)
    • 2.6 常量
    • 2.7 运算符
    • 2.8 枚举
    • 本章小结
    • 练习题

第 2 章:语法与类型系统

Python 对照表

PythonJava
动态类型 静态类型,变量类型在编译期确定
int, float, str, bool int, double, String, boolean
None null(引用类型)
x: int = 1(类型提示) int x = 1;(强制)
无 char 独立使用 char 单字符,String 字符串
一切皆对象(含 int) 基本类型 + 包装类 Integer 等

2.1 基本类型

Python:

age = 25
price = 19.99
name = "Alice"
active = True
nothing = None

Java:

int age = 25;
double price = 19.99;
String name = "Alice";
boolean active = true;
String nothing = null; // 引用类型才能为 null

Java 基本类型字节Python 近似包装类
byte 1 无直接对应 Byte
short 2 Short
int 4 int Integer
long 8 任意精度需 int 对象 Long
float 4 float Float
double 8 float Double
boolean bool Boolean
char 2 单字符 str Character

⚠️ 常见坑:int 等基本类型不能为 null;需要可空时用 Integer。

2.2 类型转换

Python:

n = int("42")
s = str(42)

Java:

int n = Integer.parseInt("42");
String s = String.valueOf(42);
// 或
String s2 = Integer.toString(42);

2.3 字符串

Python:

msg = f"User {name} has {count} items"
lines = """line1
line2"""

Java:

String msg = String.format("User %s has %d items", name, count);
// Java 15+
String lines = """
line1
line2
"""
;

操作PythonJava
长度 len(s) s.length()
子串 s[1:4] s.substring(1, 4)
包含 "ab" in s s.contains("ab")
分割 s.split(",") s.split(",")
去空白 s.strip() s.strip()(Java 11+)
不可变

2.4 数组 vs 列表

Python(列表):

nums = [1, 2, 3]
nums.append(4)

Java(定长数组):

int[] nums = {1, 2, 3};
int[] nums2 = new int[3];
nums2[0] = 1;
// 数组长度固定,增删用 ArrayList(第 6 章)

💼 面试点:数组是对象,存在堆上;int[] 存基本类型,Integer[] 存对象。

2.5 var 局部类型推断(Java 10+)

类似 Python 的直觉,但仅限局部变量且必须有初始化:

var list = new ArrayList<String>(); // 推断为 ArrayList<String>
var name = "Alice"; // 推断为 String
// var x; // 编译错误:无法推断

2.6 常量

Python:

MAX_SIZE = 100 # 约定,非强制

Java:

final int MAX_SIZE = 100;
static final double PI = 3.14159;

final 表示引用不可重新赋值(对象内容仍可能可变,如 List)。

2.7 运算符

大部分与 Python 相同。差异:

场景PythonJava
整除 7 // 2 → 3 7 / 2 → 3(两 int 相除)
真除 7 / 2 → 3.5 7.0 / 2 → 3.5
逻辑与或 and / or && / ||
not x !x
三元 a if cond else b cond ? a : b

int a = 7 / 2; // 3
double b = 7 / 2.0; // 3.5
String r = score >= 60 ? "pass" : "fail";

2.8 枚举

Python 3.4+ 有 Enum,Java 枚举更常用且功能更强:

Python:

from enum import Enum

class Status(Enum):
PENDING = "pending"
DONE = "done"

Java:

public enum Status {
PENDING("pending"),
DONE("done");

private final String label;

Status(String label) {
this.label = label;
}

public String getLabel() {
return label;
}
}

使用:Status.PENDING,可用在 switch 中(第 3 章)。


本章小结

  • Java 必须声明类型;null 只用于引用类型
  • 字符串不可变,方法名与 Python 不同(length() 不是 len())
  • 定长数组用 [],动态集合用 ArrayList 等
  • final 声明常量;枚举是企业代码常见写法

练习题

  • 将 Python 代码 total = float(input_str) * quantity 改写为 Java(input_str 为 String,quantity 为 int)。
  • 写 Java 代码判断字符串是否为回文(忽略大小写)。
  • 用 enum 定义星期 DayOfWeek,含 MONDAY 到 SUNDAY。
  • 解释 int 与 Integer 的区别及自动装箱(autoboxing)是什么。
  • 赞(0)
    未经允许不得转载:171主机测评 » Python转Java系列:语法与类型系统
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址