1. 程式人生 > >【Java】基本數據類型以及其轉換

【Java】基本數據類型以及其轉換

行數 -s www. 取值 a+b valueof eight color 比對

整理了一下Java基本數據類型和面試可能涉及的知識。

字節數(byte) 位數(bit) 取值範圍
整型 byte 1 8 -2^7 ~ 2^7 -1
short 2 16 -2^15 ~ 2^15-1
int* 4 32 -2^31 ~ 2^31-1
long 8 64 -2^63 ~ 2^63-1
浮點型 float 4 32
double* 8 64
字符型 char 2 16 0~2^16-1
布爾型 boolean 1

整型的取值範圍:

最高位為符號,正負各2^(位-1)個數,0歸為正數,故正數範圍為0~2^(位-1)-1,負數為-2^(位-1)~-1

浮點型的取值範圍:

float和double的範圍是由指數的位數來決定的。沒有搞清楚這個,遲點復習再看。

https://www.cnblogs.com/BradMiller/archive/2010/11/25/1887945.html 這篇寫得蠻好的

1. 基本數據類型之間的轉換

參考:https://www.cnblogs.com/liujinhong/p/6005714.html

低精度 →→   自動轉換   →→ 高精度
byte、char、short、int
、long、float、double
←←   強制轉換   ←←

由於Java中默認整型數據使用int,浮點型使用double,故書寫規範:

byte a = 1;         //自動轉換
byte b = (byte)128;    //數值超出範圍需作強制轉換
long c = 10000000000L;  //強制轉換
float d = 3.5f;      //強制轉換
double e = 3.5;

進行數學運算時,數據類型會轉換為涉及數據的最大形式

int a = 2;
byte b = 2;
byte c = (byte)(a+b);
double d = 5;
char ch = (char)(‘a‘+1);

char型運算時會自動提升為int類型

char a = 55;
char b = ‘a‘;
char c = (char)(a+b);
char d = ‘a‘+‘a‘;
System.out.println(a);//7
System.out.println(b);//a

2. 基本數據類型的包裝類及其轉換

基本數據類型 boolean  char byte short int long float double
包裝類 Boolean Character Byte Short Integer Long Float Double

裝箱與拆箱

Integer i = 10;  //裝箱	基本類型 → 包裝器類型
int n = i;     //拆箱	包裝器類型 → 基本類型

查看對應.class文件可發現,以上代碼實際調用的方法:

Integer i = Integer.valueOf(10);
int n = i.intValue();

Integer(指向緩存/常量池) 和 new Integer(指向堆)由於指向內存位置不一樣,比較時兩者不等。

② Integer(非new)互相比較時,數值位於int取值範圍內,比較結果為true,超出範圍則為false

③ int和Integer/new Integer比較時,由於Integer會首先作拆箱處理與int比對,所以比較結果一定為true

註:Double比較有所差別,所有Double的比較都為false

詳細可參詳:https://www.cnblogs.com/dolphin0520/p/3780005.html

【Java】基本數據類型以及其轉換