# 溢位

### 一、介紹

Java 提供 long、int、short 及 byte 四種型態最大最小值代碼；\
要使用某個型態的代碼，必須先指定該型態所在的類別庫以及該型態所屬的類別；

以下為長整數最大值的代碼示範：

![java.lang 類別庫太常使用，所以預設會將它載入，可以直接省略](/files/-M4gaMLMtu3IYhcjHwbz)

| <p><br> long</p> | int                  |                   |
| ---------------- | -------------------- | ----------------- |
| 所屬類別             | java.lang.Long       | java.lang.Integer |
| 最大值代碼            | MAX\_VALUE           | MAX\_VALUE        |
| 最大值              | 9223372036854775807  | 2147483647        |
| 最小值代碼            | MIN\_VALUE           | MIN\_VALUE        |
| 最小值              | -9223372036854775808 | -2147483648       |

|       | shore           | byte           |
| ----- | --------------- | -------------- |
| 所屬類別  | java.lang.Short | java.lang.Byte |
| 最大值代碼 | MAX\_VALUE      | MAX\_VALUE     |
| 最大值   | 32767           | 127            |
| 最小值代碼 | MIN\_VALUE      | MIN\_VALUE     |
| 最小值   | -32768          | -128           |

### 二、程式實作

以下範例：分別宣告包含java.lang 與省略，編譯看看結果是否正確。

#### 1. 輸出最大值與最小值

```
package ch03;

public class ch03_2 {

	public static void main(String[] args) {
		long lmax=java.lang.Long.MAX_VALUE;
		int imax=java.lang.Integer.MAX_VALUE;
		short smax=Short.MAX_VALUE;
		byte bmax=Byte.MAX_VALUE;

		System.out.println("Max value of long : "+lmax);
		System.out.println("Max value of int : "+imax);
		System.out.println("Max value of short : "+smax);
		System.out.println("Max value of byte : "+bmax);

//以上為最大值

		long lmin=java.lang.Long.MIN_VALUE;
		int imin=java.lang.Integer.MIN_VALUE;
		short smin=Short.MIN_VALUE;
		byte bmin=Byte.MIN_VALUE;

		System.out.println("Min value of long : "+lmin);
		System.out.println("Min value of int : "+imin);
		System.out.println("Min value of short : "+smin);
		System.out.println("Min value of byte : "+bmin);

//以上為最小值
	}

}
```

![OUTPUT](/files/-M4gacO61dwuLMiSM1Tk)

#### 2. 當輸出值溢位

以下透過上方介紹過的最大值做溢位的示範：

```
public class ch03_3 {

	public static void main(String[] args) {
		int i=Integer.MAX_VALUE;  //在此將i設為整數最大值
		int sum;

		System.out.println("i= "+i);  //先印出i 值

		sum=i+1;
		System.out.println("i+1= "+sum);  //印出 i+1 的值

		sum=i+2;
		System.out.println("i+2= "+sum);  //印出 i+2 的值
	}

}
```

OUTPUT： \
i= 2147483647 \
i+1= -2147483648 \
i+2= -2147483647

![](/files/-M4gapquqOHOEafgb2fW)

{% hint style="info" %}
溢位發生：

當整數的大小超過可以表示的範圍，而程式又沒有做數值範圍的檢查時，這個整數所輸出的值將發生紊亂，且不是預期中的執行結果，稱為「溢位」（overflow）。
{% endhint %}

{% hint style="success" %}
解決方法：加上數值範圍的檢查功能，或使用更大的表示範圍之資料型態。
{% endhint %}

#### 3. 解決溢位發生

```
package ch03;

public class ch03_3_2 {

	public static void main(String[] args) {
		int i=Integer.MAX_VALUE;  //將i設為整數最大值

		System.out.println("i= "+i);  // 印出i 值

		System.out.println("i+1= "+(i+1)); // 會發生溢位

		System.out.println("i+2= "+(i+2L)); //加上大寫L 強制型態轉換
		System.out.println("i+3= "+((long)i+3)); // 強制轉換成長整數型態

	}

}
```

OUTPUT： \
i= 2147483647 \
i+1= -2147483648 //發生溢位 \
i+2= 2147483649 //無溢位 \
i+3= 2147483650 //無溢位


---

# 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-2.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.
