JAVA 入门
数据类型
基本数据类型-8种
整数 byte short int long
浮点数 float double
字符型 char
布尔类型 boolean
No. | 数据类型 | 大小/位 | 可表示数据范围 | 默认值 |
---|---|---|---|---|
1 | byte(字节型) | 8 | -128~127 | 0 |
2 | short(短整型) | 16 | -32768~32767 | 0 |
3 | int(整型) | 32 | -2147483648~2147483647 | 0 |
4 | long(长整型) | 64 | -9223372036854775808~9223372036854775807 | 0 |
5 | float(单精度) | 32 | -3.4E38~3.4E38 | 0.0 |
6 | double(双精度) | 64 | -1.7E308~1.7E308 | 0.0 |
7 | char(字符型) | 16 | 0~255 | ’\u0000‘ |
8 | boolear | - | true或false | false |
数值类型扩展
float a = 1000000000F;
float b = 1F;
float c = a + b;
System.out.println("c==a=>" + (c==a));
float a1 = 0.1F;
double b1 = 1 / 10;
System.out.println(a1 == b1);
//银行系统需要精确的数值,需要用类:BigDecimal
//强制转换,从高向低的转换不需要强制转换,反之则需要
byte a2 = 127;
int b2 = a2;
System.out.println("b2=" + b2);
//要注意 内存溢出
int c2 = 100;
long d2 = c2;
int e2 = (int) d2;
System.out.println("e2=" + e2);
int f2 = 10_0000_0000;
int g2 = 1_0000;
int h2 = f2 * g2;
double i2 = h2;
System.out.println("i2=" + i2);
i2 = f2 * g2;
System.out.println("i2=" + i2);
i2 = (long) f2 * g2;
System.out.println("i2=" + i2);
自动类型转换
整型、实型(常量)、字符型数据可以混合运算。运算中,不同类型的数据先转化为同一类型,然后进行运算。 转换从低级到高级。
低 ------------------------------------> 高
byte,short,char—> int —> long—> float —> double
数据类型转换必须满足如下规则:
- 1.不能对boolean类型进行类型转换。
- 2.不能把对象类型转换成不相关类的对象。
- 3.在把容量大的类型转换为容量小的类型时必须使用强制类型转换。
- 4.转换过程中可能导致溢出或损失精度,例如:
int i =128;
byte b = (byte)i;
-5. 浮点数到整数的转换是通过舍弃小数得到,而不是四舍五入,例如:
(int)23.7 == 23;
(int)-45.89f == -45
强制类型转换
-
- 条件是转换的数据类型必须是兼容的。
-
- 格式:(type)value type是要强制类型转换后的数据类型 实例:
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
隐含强制类型转换
- 1、 整数的默认类型是 int。
- 2、小数默认是 double 类型浮点型,在定义 float 类型时必须在数字后面跟上 F 或者 f。