015-Java-006

xiaoxiao2021-02-28  148

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;

转载请注明原文地址: https://www.6miu.com/read-24873.html

最新回复(0)