Variables & Data Types 变量与数据类型
Learning Objectives 学习目标
- Declare and initialize primitive variables (int, double, char, boolean).
- Utilize variables and the String class to store and concatenate text data.
- Enforce the four syntax rules for variable naming in Java.
- 声明并初始化基本数据类型变量(int、double、char、boolean)。
- 利用变量和 String 类存储与拼接文本数据。
- 在 Java 中强制执行变量命名的四个语法规则。
2 · Variable Declarations & Initializations
A variable is a named memory location in the computer's RAM. It holds values that can change during program execution. To use a variable in Java, it must first be declared (defining its type and name) and initialized (assigning a starting value): 变量是计算机 RAM 中一个命名的存储单元。它保存程序执行期间可以改变的值。要在 Java 中使用变量,必须首先进行声明(定义其类型和名称)并初始化(赋予初始值):
int score; // Declaration score = 95; // Initialization / Assignment int total = 100; // Combined Declaration & Initialization
3 · Primitive Data Types
Java is a strongly-typed language, meaning every variable must have a declared type. There are 8 primitive data types. We focus on the core 4: Java 是一种强类型语言,这意味着每个变量都必须有一个声明的类型。共有 8 种基本数据类型。我们专注于核心的 4 种:
| Type类型 | Bytes字节大小 | Description描述 | Example Declaration声明示例 |
|---|---|---|---|
| int | 4 bytes | Stores whole integers without decimals.存储不带小数的整数。 | int count = 25; |
| double | 8 bytes | Stores floating-point fractional decimals.存储带小数点的浮点数。 | double price = 19.99; |
| char | 2 bytes | Stores a single Unicode character enclosed in single quotes.存储由单引号括起来的单个字符。 | char grade = 'A'; |
| boolean | 1 bit (JVM dependent) | Stores logical values: true or false.存储逻辑值:true 或 false。 |
boolean isTaxed = true; |
4 · The String Class
Unlike primitive types, String is a reference class type in Java. It is used to store multiple text characters enclosed in double quotes. Strings can be joined (concatenated) using the + operator:
与基本类型不同,String 是 Java 中的引用类类型。它用于存储由双引号括起来的多字符文本。可以使用 + 运算符将字符串拼接在一起:
String firstName = "Chee"; String lastName = "How"; String fullName = firstName + " " + lastName; // "Chee How" System.out.println("User: " + fullName);
5 · Variable Naming Constraints
Java enforces strict rules for variable names (identifiers). Violating these results in compile errors: Java 对变量名称(标识符)强制执行严格的规则。违反这些规则将导致编译错误:
The Four Core Rules四个核心规则
-
No Keywords:不能是关键字: Names cannot be Java reserved words (e.g.,
class,double,int).名称不能是 Java 保留字(例如class、double、int)。 -
Start Characters:起始字符限制: Must begin with a letter (A-Z, a-z), underscore (
_), or dollar sign ($). It cannot begin with a number.必须以字母(A-Z、a-z)、下划线(_)或美元符号($)开头。不能以数字开头。 -
No Spaces/Symbols:无空格或特殊符号: No spaces or special characters (like
!,@,#,-) are allowed. Only$and_are valid.不允许有空格或特殊字符(如!、@、#、-)。只有$和_是有效的。 -
Case Sensitivity:大小写敏感: Java treats upper and lowercase letters differently (e.g.,
totalScoreandtotalscoreare separate variables).Java 区分大小写字母(例如,totalScore和totalscore是不同的变量)。
Applied Case Study: Store Inventory Registry应用案例研究:商店库存登记
Company: Kompas Snack Shop.
We design variables to store product details: inventory item name, available stock counts, price, and taxable status.
公司: Kompas Snack Shop。
我们设计变量来存储产品详细信息:库存商品名称、可用库存数量、价格以及是否纳税的状态。
Snack Inventory Source Code零食库存程序源代码
public class SnackInventory {{ public static void main(String[] args) {{ String snackName = "Kompas Potato Chips"; int stockQuantity = 120; double unitPrice = 3.50; char packageSize = 'L'; boolean isTaxable = false; System.out.println("Product Details:"); System.out.println("Name: " + snackName); System.out.println("Stock: " + stockQuantity + " units"); System.out.println("Price: RM " + unitPrice); System.out.println("Size: " + packageSize); System.out.println("Taxable: " + isTaxable); }} }}
💡 Hint / 提示
Notice how we declare appropriate data types for different inputs. Text uses String, numeric counts use int, monetary items use double, size symbols use char, and flag fields use boolean.注意我们如何为不同的输入声明合适的数据类型。文本使用 String,数字计数使用 int,金额使用 double,尺寸符号使用 char,标志字段使用 boolean。
✅ Show Expected Console Output / 显示预期控制台输出
Product Details: Name: Kompas Potato Chips Stock: 120 units Price: RM 3.5 Size: L Taxable: false
Check Your Understanding自我检测
Q1. Which of the following is a valid variable name in Java?以下哪个是 Java 中有效的变量名称?
Q2. Which primitive data type is best suited for storing monetary prices (e.g., 19.99)?哪个基本数据类型最适合存储货币价格(例如,19.99)?
Q3. Which data type is NOT a primitive type in Java?在 Java 中,哪个数据类型不是基本数据类型?
Q4. Evaluate the output of variables: int a = 5; int b = a; b = 10; What is value of variable a?评估变量输出结果:int a = 5; int b = a; b = 10; 变量 a 的值是什么?