015-Java-006

Java常量

final double PI = 3.1415927;

自动类型转换

转换从低级到高级。

  ------------------------------------>  

byte,short,char—> int —> long—> float —> double 
1. 不能对boolean类型进行类型转换。

2.在把容量大的类型转换为容量小的类型时必须使用强制类型转换

3. 转换过程中可能导致溢出或损失精度,例如:

int i =128;   
byte b = (byte)i;

因为byte类型时8位,最大值为127,所以当强制转换为int类型值128时候就会导致溢出。

4. 浮点数到整数的转换是通过舍弃小数得到,而不是四舍五入,例如:

(int)23.7 == 23;		
(int)-45.89f == -45

自动类型转换

public class ZiDongZhuanHuan{
	public static void main(String []args){
		char c1='a'; //定义一个char类型
		int i1=c1; //char自动类型转换为int
		System.out.println("char自动类型转换为int后的值等于" + i1);
		char c2 = 'A';
		int i2 = c2=1;
		System.out.println("char类型和int计算后值等于" + i2);
	}
}

结果:

char自动类型转换为int后的值等于97
char类型和int计算后值等于1

强制类型转换

public class QiangZhiZhuanHuan{
    public static void main(String[] args){
        int i1 = 123;
        byte b = (byte)i1;//强制类型转换为byte
        System.out.println("int强制类型转换为byte后的值等于"+b);
    }
}
int强制类型转换为byte后的值等于123


Java 里使用 long 类型的数据一定要在数值后面加上 L,否则将作为整型解析:

long g = (long)9223372036854775807;
long h = (long)-9223372036854775808;

或者

long g = 9223372036854775807;
long h = -9223372036854775808;

会出现以下报错信息:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The literal 9223372036854775807 of type int is out of range
The literal 9223372036854775808 of type int is out of range 

溢出了~

解决方法在数值后面加上 L

long value = 9223372036854775807L;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值