java简单数据类型的知识点

今天谈谈简单数据类型,包括byte,short,char,int,long,float,double,内容是溢出和类型转换。

 1 package BasicType;
 2 
 3 public class BasicTypeTest {
 4 
 5     public static void main(String[] args) {
 6 
 7         //一、关于溢出
 8         
 9         int balance = 2147483647;//整型的最大值,即2的31次方减1
10         balance += 1;
11         System.out.println(balance);//内存溢出,输出了int型的最小值,这里没有报错,但我们必须避免
12         
13 //        int a1 = 10000000000;编译不通过,超出int范围
14         int a2 = 1000000000 * 10;
15         System.out.println(a2);//内存溢出,运行时才知道结果
16         
17         //溢出与长整型
18 //        long z = 10000000000;编译错误,不加L,10000000000默认为int型,这里就超出int的范围了
19         
20         long a3 = 1000000000 * 2 * 10L;
21         System.out.println(a3);//没有发生溢出
22         
23         long a4 = 1000000000 * 3 * 10L;
24         System.out.println(a4);//1000000000 * 3时就发生溢出了
25     
26         long a5 = 1000000000L * 3 * 10;
27         System.out.println(a5);//为防止溢出,在第一个数字后面加L转化成长整型
28         
29         //类型强制转换时发生溢出
30         long a6 = 1024L * 1024 * 1024 * 4;
31         int i = (int) a6;
32         System.out.println(i);//0
33         
34         
35         //二、关于类型转换
36         //小类型到大类型的顺序:byte->short->int->long->float->double
37         //char的本质也是数值,也可和int并列
38         
39         //char和int的转换
40         char c1 = 65;
41         System.out.println(c1);//输出为A,系统自动将65转为对应的ASCII码了
42         
43         int c2 = 'A';
44         System.out.println(c2);//输出为65
45         
46         char c3 = '\u0041';
47         System.out.println(c3);//输出为A,Unicode编码是16进制的,65转为16进制就是0041
48         
49         //小类型向大类型转是自动完成的
50         //整数字面量默认为int,小数字面量默认为double
51         long a7 = 5000;//隐式地将整型转换成了长整型
52 //        float f = 45.5;编译错误,45.5默认为double,需要类型强转
53         
54         //整型与整型做除法得到的还是整型
55         double d = 50 / 200;
56         System.out.println(d);//输出为0.0
57         
58         //强转可能导致精度丢失
59         double e = 2.718281828459045;
60         float f = (float) e;
61         System.out.println(f);//输出为2.7182817
62         
63         //int字面量可以直接赋给byte,char,short
64         byte b = 5;//5默认为int,要把它存在变量b中,理应进行类型强转,但这里只要不超出byte范围即可
65         
66         //byte,char,short参与运算时,都是先转为int再进行运算,因为int有更大的空间,防止经常发生内存溢出
67         byte b1 = 5;
68         byte b2 = 6;
69 //        byte b3 = b1 + b2;编译错误,b1和b2此时变成了int型,要进行强转
70         byte b3 = (byte) (b1 + b2);
71         
72         System.out.println(1 + '1');//char类型转换成了对应的ASCII的值,即49,再进行加法运算得到50
73         
74     }
75 
76 }

猜你喜欢

转载自www.cnblogs.com/stoneandatao/p/10447990.html