Variables and Data Types
| English | Chinese | Pinyin |
|---|---|---|
| variable | 变量 | biàn liàng |
| primitive types | 基本类型 | jī běn lèi xíng |
| reference types | 引用类型 | yǐn yòng lèi xíng |
A variable is a labelled box
- A variable 变量 is a named place in memory that stores a value.
- Give it a type, a name, and (usually) a starting value:
int score = 0; - Read it or change it by name; the box holds the latest value.
- Every variable in Java must be declared with a type before use.
The primitive types
- Java has eight primitive types 基本类型; four matter most for AP:
int— whole numbers (e.g.42).double— decimals (e.g.3.14).boolean—trueorfalse.char— a single character ('A').- Primitives store the actual value directly in the box.
Reference types
- Non-primitive types (like
String) are reference types 引用类型. - A reference variable stores the address of an object, not the object itself.
String name = "Ada";—namepoints to a String object.- Primitive vs. reference is a distinction you'll use all course.
Naming and declaring
- Names start with a letter; use camelCase (
highScore,numStudents). - Declaring reserves the box; initializing gives it a first value.
- A
finalvariable is a constant — its value can't change after it's set. - Choose clear names — code is read far more than it's written.
int and double are different types — mind the division. int division throws away the remainder: 7 / 2 is 3, not 3.5. To get 3.5, at least one operand must be a double (7.0 / 2). Storing a decimal in an int won't even compile without a cast. Pick the type that matches the values you need.
Tracing a few declarations:
int radius = 5;→ the boxradiusholds5.double pi = 3.14159;→piholds3.14159.radius = 10;→ the same box now holds10(the old5is gone).
A variable is a typed, named storage box. The core primitive types are int, double, boolean, and char, which store a value directly; reference types like String store the address of an object. Declare with a type, use camelCase, and remember int division drops the remainder.
Tracing variable values
Step through to watch each box take its value.
Which type stores whole numbers like 42?
int stores integers; double stores decimals.
In Java, what is the value of the int expression 7 / 2?
int division drops the remainder: 7/2 = 3.
A variable that stores the address of an object (not the value itself) has a...
String and other objects are reference types.
Which is the conventional Java naming style for a variable?
Variables use camelCase in Java.
A variable declared final can have its value changed later.
final makes it a constant — the value can't change.