Java基礎:資料類型

來源:互聯網
上載者:User

1.  分類


基礎資料型別 (Elementary Data Type)

4 類 8 種 --> 

邏輯型 boolean  文本型 char  整數型 byte short int long  浮點型 float double

 

引用資料類型

3類      --> 

類 class    介面 interface     數組

 

2. 基礎資料型別 (Elementary Data Type)


 <1> 資料提升:運算之前,先轉換為高一級的資料類型再運算,規則如下:

   byte  short  char ---> int ---> long ---> float ---> double
    1       2        2             4           8             4              8  -->octets

   byte short char 之間不會相互提升,boolean不會轉化為其他資料類型.

   byte 範圍:-128 ~ 127

   byte short char 在參加運算時,會自動轉化為 int,再運算。


   如:byte b1 = 1;
         byte b2 = 2;
         byte b3 = b1 + b2 ;報錯
         //byte b3 = (byte)b1+b2;  聯想到 short char 也是如此


 <2> 資料聲明

  整型量會預設為 int 類型,所以 long 類型後面要加 l 或者 L

  long a = 20L;                 long a = 20l; 

  再如:long l = 2000000000;//不加L或者l就會報錯(過大的整數)

 

  因為編譯器看到整型數就視為int但是int只有四個位元組裝不下2000000000就報錯!
  
  浮點數會預設為 double 類型,所以float類型後面要加 f 或者 F

  float f = 2.3F;               float f = 2.3f;
  
  建議:聲明 long 或者 float 資料類型時寫上F 或者 L,不要使用小寫 f 或者 l。


猜猜下面程式列印結果?

public class OnLongDemo {// 年的微秒數private static final long MICROS_PER_YEAR = 365 * 24 * 60 * 60 * 1000 * 1000;// 年的毫秒數private static final long MILLIS_PER_YEAR = 365 * 24 * 60 * 60 * 1000;public static void main(String[] args) {System.out.println(MICROS_PER_YEAR/MILLIS_PER_YEAR);}}


那麼,修改一下代碼

public class OnLongDemo {// 年的微秒數private static final long MICROS_PER_YEAR = 365L * 24 * 60 * 60 * 1000 * 1000;// 年的毫秒數private static final long MILLIS_PER_YEAR = 365L * 24 * 60 * 60 * 1000;public static void main(String[] args) {System.out.println(MICROS_PER_YEAR/MILLIS_PER_YEAR);}}


再看一個小程式,就可以知道為什麼要寫大寫字母 L, 而不寫小寫字母l

public class OnLongDemo {public static void main(String[] args) {long x = 1234;long y = 432l;System.out.println("x+y= " + (x+y));}}

很多人,一看列印結果是 x+y= 5555,但是你錯了!!




long y = 432l 後面不是數字 1,而是小寫字母 l









相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.