1. 程式人生 > >資料型別 與 運算子

資料型別 與 運算子

1.識別符號

  • 作用:給變數,類和方法命名
  • 規則:

  1>以字母、下劃線(“_”)、美元符號(“$”)開頭
  2>其他部分由字母、下劃線、美元符號、數字的任意組合
   3>對大小寫敏感,無長度限制但不可用關鍵字作為識別符號

✦Java關鍵字

byte short int long boolean
char float double if else
do while switch break default
goto case for return try
abstract continue enum new assert
package synchronized private this implements
protected throw throws import public
static void instanceof transient catch
extends final finally interface class
strictfp volatile const native super

注:命名時為了增強程式的可讀性,基本不單獨使用下劃線(_)來命名,且有的公司宣告不可用美元符號($)來命名。

2、資料型別

在這裡插入圖片描述

  • 基本資料型別
資料型別 包裝類 預設值 佔用儲存空間 範圍
整型 byte Byte 0 1位元組 -128~127
整型 short Short 0 2byte - 2^15 ~ 2^15 - 1
整型 int Integer 0 4byte - 2^31 ~ 2^31 - 1
整型 long Long 0L 8byte - 2^63 ~ 2^63 - 1
浮點型 float Float 0.0f 4byte -3.403E38~3.403E38
浮點型 double Double 0.0d 8byte -10798E308~1.198E308
字元型 char Character \u0000 2byte \u0000~\uffff
布林型 boolean Boolean false ture/false
  • 引用資料型別
資料型別 說明
類 型別

1>Java類庫中定義的類(eg:Object、String、Date)和使用者定義的類

2>Java類庫中定義的列舉(enum)和使用者定義的列舉

介面 型別

1>Java類庫中定義的介面和使用者定義的介面

2>Java類庫中定義的註解和使用者定義的註解

陣列 型別 一維和多維陣列
null 型別 null 型別為空引用型別,使用 null 常量來表示
  • 型別轉換

  - 小型別轉化為大型別自動轉換
  - 大型別轉化為小型別需要強制轉換
特例:在不超過其表數範圍的情況下,可以將整型常量直接賦值給byte、short、char 等型別變數,不需要進行強制轉換


short b = 5;//合法
short c = 1234567;//非法

1>自動型別轉換(隱式轉換)
注意:隱式轉換可能會降低精度,eg:從 long 到 float 的轉換

在這裡插入圖片描述
注:白色箭頭表示可能會降低精度

轉 換 源 轉 換 目 標
byte short、int、long、float、double
short int、long、float、double
int long、float、double
long float、double
char int、long、float、double
float double

注:不存在到 char 型別的隱式轉換

  • 如果整型常量超過變數範圍,則會產生編譯錯誤。例如:

byte b11 = 123;//整型常量 123 從 int 到 byte 的自動轉換
short s1 = 123;//整型常量 123 從 int 到 short 的自動轉換
long long1 = 123;//整型常量 123 從 int 到 long 的自動轉換
float f1 = 123;//整型常量 123 從 int 到 float 的自動轉換
double d1 = 123;//整型常量 123 從 int 到 double 的自動轉換
byte b22 =255;//編譯錯誤,byte 的取值範圍為 -128~127

2>強制型別轉換(顯示轉換)
注:顯示轉換可能會導致精度損失,也可能由於溢位而導致轉換結果不正確


byte b1 = (byte)12.3;//結果:12,精度損失
byte b2 = (byte)128;//結果:-128,由於溢位從而導致轉換結果不正確

轉 換 源 轉換目標
short byte、char
int byte、short、char
long byte、short、char、int
float byte、short、char、int、long
double byte、short、char、int、long
char byte、short

3、優先順序順序

優先順序 運算子 簡介 結合性
1 [ ]、. 、() 方法呼叫,屬性獲取 從左向右
2 !、~、++、– 一元運算子 從右向左
3 *、/、% 乘、除、取模(餘數) 從左向右
4 +、- 加減法 從左向右
5 <<、>>、>>> 左位移、右位移、無符號右移 從左向右
6 <、<=、>、>= 小於、小於等於、大於、大於等於 從左向右
7 ==、!= 判斷兩個值是否相等、判斷兩個是是否不等 從左向右
8 & 按位與 從左向右
9 ^ 按位異或 從左向右
10 按位或 從左向右
11 && 短路與 從左向右
12 丨丨 短路或 從左向右
13 ?: 條件運算子 從右向左
14 =、+=、-=、/=、%=、&=、丨=、^=、<、<=、>、>=、>>= 混合賦值運算子 從右向左