/** * * 转换基本数据类型 * */ public class ChangeBasicType { /** * 基本类型的数据提升 */ private void typeAutoUpgrade() { byte b = 44; char c = 'b'; short s = 1024; int i = 40000; long l = 12463l; float f = 35.67f; double d = 3.1234d;
/** * 强制类型转换 * 当两种类型不兼容,或者目标类型范围比源类型范围小时,必须进行强制类型转换 * 具体转换时会进行截断,取模操作 */ private void forceChange() { double d = 123.456d; float f = (float)d; long l = (long)d; int i = (int)d; short s = (short)d; byte b = (byte)d; System.out.println("d = " + d + "; f = " + f + "; l = " + l); System.out.println("i = " + i + "; s = " + s + "; b = " + b );
d = 567.89d; /* * 下面的转换首先进行截断操作,将d的值变为567,因为567比byte的范围256大。 * 于是进行取模操作,567对256取模后的值为55 */ b = (byte)d; System.out.println("d = " + d + "; b = " + b); }
public static void main(String args[]) { ChangeBasicType cbt = new ChangeBasicType(); System.out.println("===================基本类型自动提升====================="); cbt.typeAutoUpgrade(); System.out.println("===================基本类型自动的转换===================="); cbt.autoChange(); System.out.println("===================强制类型转换========================="); cbt.forceChange(); } }