---------------------- android培訓 、java培訓 、期待與您交流! ----------------------
基本數據類型轉換
java有8種基本數據類型 分別是:1. 布爾類型 boolean (佔1個字節)。 2.字符型 char (佔2個字節) .3 整數型: byte(佔1個字節) short(佔2個字節) int(佔4 個字節) long(佔8個字節)。 實數型 float(佔4個字節) double(佔8個字節)。
類型轉換的時候遵循以下規律 1 容量小的 自動轉換爲容量大的數據類型 容量大小順序爲 byte ,short , char>int >long>float>double.。 byte ,short char之間不會互相轉換。他們在計算是 先轉爲int型 2 容量大的轉換爲容量小的 需要強制轉換,但可能造成精度降低或溢出。3 有多種類型混合運算是 自動轉換爲容量最大的數據類型,然後在進行計算。4 實數常量默認爲double 整數常量 默認爲 int
public class TestConvert {
public static void main(String arg[]) {
int i1 = 123;
int i2 = 456;
double d1 = (i1+i2)*1.2;//系統將轉換爲double型運算
float f1 = (float)((i1+i2)*1.2);//需要加強制轉換符
byte b1 = 67;
byte b2 = 89;//int類型自動轉換爲byte類型,但這裏需注意值不能超過byte的範圍
byte b3 = (byte)(b1+b2);//系統將轉換爲int型運算,需
//要強制轉換符
System.out.println(b3);
double d2 = 1e200;
float f2 = (float)d2;//會產生溢出
System.out.println(f2);
float f3 = 1.23f;//必須加f
long l1 = 123;
long l2 = 30000000000L;//必須加l
float f = l1+l2+f3;//系統將轉換爲float型計算
long l = (long)f;//強制轉換會捨去小數部分(不是四捨五入)
}
}
---------------------- android培訓 、java培訓 、期待與您交流! ----------------------
詳細請查看:http://edu.csdn.net/heima