了解Java编程语言的朋友都知道,在Java中存在不同的数据类型,在实际编写程序代码时,会遇到数据类型之间转换的现象,Java基本数据类型之间有自动类型转换与强制类型转换两种转换方法,下面,济宁网站建设小编就来和大家一起来看看两种类型转换示例代码,有兴趣的朋友可以过来关注一下。
1、自动类型转换
public class AutoTypeCasting {
public static void main(String[] args) {
int intValue = 100;
long longValue = intValue; // 自动类型转换,int -> long
System.out.println("Int value: " + intValue);
System.out.println("Long value after auto casting: " + longValue);
float floatValue = 10.5f;
double doublevalue = floatValue; // 自动类型转换,float -> double
System.out.println("Float value: " + floatValue);
System.out.println("Double value after auto casting: " + doublevalue);
}
}
2、强制类型转换
public class ExplicitTypeCasting {
public static void main(String[] args) {
double doublevalue = 20.6;
int intValue = (int)doublevalue; // 强制类型转换,double -> int
System.out.println("Original double value: " + doublevalue);
System.out.println("Int value after explicit casting: " + intValue);
long longValue = 123456789L;
short shortValue = (short)longValue; // 强制类型转换,long -> short
System.out.println("Original long value: " + longValue);
System.out.println("Short value after explicit casting: " + shortValue);
}
}