[toc]
# 宣告變數
告訴compiler你要用name去refer一個資料, 它的type是*type*
寫法:
```
type name;
```
```
type var1, var2, var3;
```
---
## 變數命名規則
- 不可使用關鍵字
- 開頭只能用`A-Z`, `a-z`, `_`, `$`
- 其他只能用`A-Z`, `a-z`, `_`, `$`, `0-9`
- 沒有長度上限
(Java編譯期間自己建立的變數會以`$`開頭, 因此儘量不要使用`$`)
## Three Types of Variables
- 在class內, Method外, 叫做 "member variable" ("成員變數"), "field"
- 在Method裡面的, 叫做local variable
- 宣告Method中寫的, 叫做參數(parameter)
```java=
class Main {
int i; // field
public static int add(int a, int b) { // parameter
int result = a + b; // local variable
return result;
}
}
```
## 初始值
- **member variable (field)**
如果沒有寫初始值, 會直接使用該原始型別的初始值。
但這不是一個好的程式風格。
- 初始值
- Primitive Type: default value
- Reference Type: null
- **local variable**
不會有初始值。
存取未初始化的局部變數會有CE。
- 初始值
- Primitive Type: not initialized
- Reference Type: not initialized
```java=
public class Main {
int i; // 0
Object o; // null
// you should always write the initial value.
int j = 0;
Object obj = null;
public static void main(String[] args) {
int i; // not initialized
Object o; // not initialized
}
}
```