1.同类型转换
public class Test2 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int x = Integer.MAX_VALUE; //得到整型的最大值
System.out.println(" x = " +x);
System.out.println(" x+1 =" + (x+1) );//整型类型溢出
System.out.println(" x+2 =" + (x+2L) );//为了避免溢出发生,在表达式的常量部分2后加上L
System.out.println(" x+3 =" + ((long)x+3) );//为了避免溢出发生,在表达式的整数部分x之前加long
System.out.println(" x+2 =" + ((long)x+2) );
}
}
在常量后加L,在变量前加long,都能实现强制类型转换
2.不同类型转换
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner input = new Scanner(System.in);
try {
System.out.println("Please input the distance you ran: kil = ");
double km= input.nextDouble();
double mile = 1.6*km;
System.out.println("Please input the time you spent: h = ");
double h = input.nextDouble();
System.out.println("min = ");
int min = input.nextInt();
System.out.println("s = ");
int s = input.nextInt();
h = h + (double)min/60 + (double)s/3600;
System.out.println("The speed is "+(mile/h)+" mile/h");
}
finally {
input.close();
}
}
首先要说的是,不同数据类型是不能随意转换的,例如
int a = 2;
double b = 3;
a = b;
如此一来,a的值会直接变成0
此时,可以进行强制数据类型转换,对a赋值时,在b前面加一个(double),就可以进行强制数据类型了。