Java基本數據類型轉換
public class TestConvert {
public static void main(String arg[])
{
int i1 = 123;
int i2 = 456;
double d1 = (i1+i2)*1.2;//系統(tǒng)將轉換為double型運算
float f1 = (float)((i1+i2)*1.2);//需要加強制轉換符
byte b1 = 67;
byte b2 = 89;
byte b3 = (byte)(b1+b2);//系統(tǒng)將轉換為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;//系統(tǒng)將轉換為float型計算
long l = (long)f;//強制轉換會舍去小數部分(不是四舍五入)
}
}
public class TestConvert2 {
public static void main(String[] args) {
int i=1,j=12;
float f1=(float)0.1; //0.1f
float f2=123;
long l1 = 12345678,l2=8888888888L;
double d1 = 2e20,d2=124;
byte b1 = 1,b2 = 2,b3 = 127;
j = j+10;
i = i/10;
i = (int)(i*0.1);
char c1='a',c2=125;
byte b = (byte)(b1-b2);
char c = (char)(c1+c2-1);
float f3 = f1+f2;
float f4 = (float)(f1+f2*0.1);
double d = d1*i+j;
float f = (float)(d1*5+d2);
}
}