java基礎02 資料類型轉換

來源:互聯網
上載者:User

標籤:bsp   byte   資料類型   精度   str   符號   logs   數值   截取   

一、回答問題
float f1 = 6.66f;
float f2 = (float) 6.67;

f1==f2?

/** *  * @author sun * */public class Demo {public static void main(String[] args) {float f1 = 6.67f;float f2 = (float) 6.66;System.out.println(f1-f2);System.out.println(f1==f2);}}

輸出:

0.010000229
false

為什麼會出現這種情況呢?f1!=f2呢?這時我們要知道,在Java中,

整數預設是int類型,浮點數預設是double。
長整數要加L或者l。
單精確度的浮點數要加F或者f。

預設轉換
A:從小到大
B:byte,short,char -- int -- long -- float -- double

後者6.66是個double類型的,經過強制轉換賦值給f2,會丟失精度,所以出現上述情況。

二、下面的程式有問題嗎,如果有,在哪裡呢?
byte b1 = 3;
byte b2 = 4;
byte b3 = b1 + b2;
byte b4 = 3 + 4;

b1+b2java中是自動轉換成int型在計算值的 結果是int型的資料,不能自動轉成byte,所以報錯,需要強制轉化為byte。
三、下面的操作結果是什麼呢?
byte b = (byte)130;

/** *  * @author sun * */public class Demo {public static void main(String[] args) {// 因為byte的範圍是:-128到127。(-2^7--2^7-1)// 我們需要使用強制類型轉換byte b = (byte) 130;System.out.println(b);}}

輸出:

-126

 分析過程: 我們要想知道結果是什麼,就應該知道是如何進行計算的。 而我們又知道電腦中資料的運算都是補碼進行的。 而要得到補碼,首先要計算出資料的二進位。
 A:擷取130這個資料的二進位。 00000000 00000000 00000000 10000010 這是130的原碼,也是反碼,還是補碼。
 B:做截取操作,截成byte類型的了。 10000010 這個結果是補碼。 C:已知補碼求原碼。 符號位 數值位 補碼: 1 0000010
反碼: 1 0000001
原碼: 1 1111110
 
四、字串參與運算

/** *  * @author sun * */public class Demo {public static void main(String[] args) {System.out.println("hello"+‘a‘+1);System.out.println(‘a‘+1+"hello");System.out.println("5+5="+5+5);System.out.println(5+5+"=5+5");}}

輸出:

helloa1
98hello
5+5=55
10=5+5

字串的拼接

 

 

 

java基礎02 資料類型轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.