---
# System prepended metadata

title: Primitive Data Type
tags: [Java]

---

[toc]

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

## 8 Different Primitive Data Types
| Type | Size(bit) | Limit/Details | Default Value (Field) |
| -------- | -------- | -------- | -------------- |
| byte     | 8     | -128 ~ 127     |0|
| short     | 16     | -32768 ~ 32767     |0|
| int     | 32     | -2147483648 ~ 2147483647     |0|
| long     | 64     | -2^63 ~ 2^63-1     |0L|
| float     | 32     | (1+8+23) (see IEEE754)     |0.0F|
| double     | 64     | (1+11+52) (see IEEE754)     |0.0D|
| char     | 16     | 0 ~ 65535      |\u0000|
| boolean     | 1      | true / false     |false|

- byte
8-bit signed two's complement integer

- short
16-bit signed two's complement integer

- int
32-bit signed two's complement integer

- long
64-bit signed two's complement integer

- float
single-precision 32-bit IEEE 754 floating point

- double
double-precision 64-bit IEEE 754 floating point

- boolean
true and false, the size is not declared btw.

- char
single 16-bit Unicode character
'\u0000' (0) to '\uffff' (65535)
---
宣告Primitive變數的時候, 
會使用一個約4bytes大小 + (符合該型別大小->不一定) 的記憶體空間。 [(link)](
https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html)
因此Primitive在賦值時只有值的複製。

範例程式:
```
int i; // 宣告i變數, 值等於初始值(詳見### Default Value)
i = 3; // 把i設為3
```
等同於:
```
int i = 3;
```

---
## Literals

### 整數
如果整數L/l結尾, 則為long, 否則為int. (建議使用大寫)
```java
10000; // int
2147483650L; // long
2147483650; // invalid

int i = 10000; // 10000 int
int i2 = 2147483650L; // invalid
int i3 = 2147483650; // invalid

long l = 10000; // 10000 long
long l2 = 2147483650L; // 2147483650 long
long l2 = 2147483650; // invalid
```

---

使用不同數字系統來表示數值
```java
// number 26 in decimal
int decVal = 26;

// number 26 in octal
int octVal = 032;

// number 26 in hexadecimal
int hexVal = 0x1a;
int hexVal2 = 0x1A;

// number 26 in binary
int binVal = 0b11010;
``` 
---

### 浮點數
如果以以F/f結尾, 則為float, 否則為double, 並且可選擇以D/d結尾. (建議使用大寫)
也可使用E/e來表示科學記號
```java
123.4 // double
1.234e2 // 科學記號
1.234f // float
```

### charr, boolean
```java
char c = '\u2001';
char c2 = 'a';
char c3 = 492;
  
boolean b = true;
boolean b2 = false;
```

### 底線
可以在數字之間任意新增底線`_`, 除了:
- 數字的頭尾
```java
int i = _123; // invalid
int i2 = 1_23; // valid
int i3 = 123_; // invalid
int i4 = 0x_123; // invalid
```
- 小數點左右
```java
float f1 = 3_.1415F; // invalid
float f2 = 3._1415F; // invalid
```
- F/L/D之前
```java
long l = 9999_L; // invalid
```
- 插在radix前/中/後
```java
int i4 = _0x52; // invalid
int i5 = 0_x52; // invalid
int i6 = 0x_52; // invalid
```
