# 認識變數與資料型態

> Java 變數是利用宣告方式，將記憶體某個區塊保留下來供程式使用。 可以宣告這個區塊記載的資料為 整數、字元、浮點數或是其他類型的型態，以便作為變數的儲存空間使用。

### 一、資料型態

資料型態可分為「原始資料型態」與 「非原始資料型態」。

原始資料型態也稱基本資料型態：包括整數與浮點數等型態。\
非原始資料型態是以一種特殊方式指向變數的實體；類似於C語言的指標，在 Java 稱之為參考。

如果變數值不會變動，可以直接利用 final 關鍵字將變數宣告成 final，來防止變數在程式其他地方被修改，下方為範例：

```
final 資料型態 變數名稱 = 值
```

{% hint style="info" %}
再次注意：使用 final 設定初值後就不會再改變，我們稱之為常數(constant)
{% endhint %}

舉例來說：計算圓面積，可宣告圓周率 PI=3.1415926 為常數，以確保不小心誤改；

```
final double PI=3.1415926;
```

{% hint style="info" %}
通常我們會以英文大寫字母為常數名稱命名，另外final 也有其他用途；他可以終止繼承。
{% endhint %}

無論在哪一個作業系統，Java 裡相同的資料型態均具有相同的位元組。

| 資料型態    | 位元組 | 初始值      | 範圍                                         |
| ------- | --- | -------- | ------------------------------------------ |
| long    | 8   | 0L       | -9223372036854775808 ～ 9223372036854775807 |
| int     | 4   | 0        | -2147483648 ～ 2147483647                   |
| short   | 2   | 0        | -32768 ～ 32767                             |
| byte    | 1   | 0        | -128 ～ 127                                 |
| char    | 2   | ‘\u0000’ | <p>0～ 65535<br>(‘\u0000’ – ‘\uffff’)</p>   |
| boolean | 1   | false    | ture 或 false                               |
| float   | 4   | 0.0F     | -3.4E38 ～3.4E38                            |
| double  | 8   | 0.0D     | -1.7E308 ～1.7E308                          |

### 二、程式實作

試試看以下的程式碼：

```
package ch03;

public class ch03 {

	public static void main(String[] args) {

		long num=32967359818;
		System.out.println("num= "+num);

	}

}
```

這是一個錯誤的範例，32967359818 超出int 型態，即使我們已經將型態設為long。\
那麼該如何解決呢？

只要在指數值後面加上一個大寫L 即可 (小寫亦可，易與1混淆，因此不建議)

```
long num=32967359818L;
```

這時再次編譯試試，即可成功編譯。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java.4-x.tw/java-03-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
