一、数据类型
1B(byte,字节)= 8bit(位)
byte b = 0;//字节型
short s = 0;//短整型
int i = 0;//整型
long l = 0L;//长整型
float f = 0.0f;//单精度浮点型
double d = 0.0;//双精度浮点型
boolean flag = false;//布尔值
char c = 'C';//字符型
String S = "String";//字符串是一个类,属于引用数据类型
1.1 整数拓展
二进制:
int i1 = 0b10;//2
八进制:
int i2 = 010;//8
十六进制:
int i3 = 0x10;//16
1.2 浮点数拓展
浮点数:有限、离散、舍入误差、接近但不等于
最好避免使用浮点数进行比较
float f = 0.1f; //0.1
double d = 1.0/10; //0.1
System.out.println(f == n); //~ false
float d1 = 2333333333333333333f;
float d2 = d1 + 1;
System.out.println(d1 == d2); //~ true
数学工具类:BigDecimal,银行存储金额
1.3 字符串拓展
String Sa = new String("Hello world");
String Sb = new String("Hello world");
System.out.println(Sa == Sb); //~ false
//创建String对象,对比两个对象所存放的地址
String Sc = "Hello world";
String Sd = "Hello world";
System.out.println(Sc == Sd); //~ true
//创建String类型的变量,对比两个变量的值
二、类型转换
高低:字节数的多少,类的父子关系。
//从低到高
byte -> short -> char -> int -> long -> float -> double
运算中,不同类型的数据先转化为同一类型,再进行运算。
强制类型转换:高–>低
int i = 128;
byte b = (byte)i; //内存溢出,byte最大为127
System.out.println("i: " + i); //~ i: 128
System.out.println("b: " + b); //~ b: -128
自动类型转换:低–>高
char c = 'a';
int d = c+1;
System.out.println(d); //~ 98
溢出
int money = 10_0000_0000; //(JDK7新特性,数字可以用下划线分割)
System.out.println(money); //~ 1000000000
int years = 20;
int total = money*years;
System.out.println(total); //~ -1474836480
//total: int类型内存溢出
long total2 = money*years;
System.out.println(total2); //~ -1474836480
//total2: 先以int类型计算money*years,再转化为long
long total3 = money*((long)years);
System.out.println(total3);//~ 20000000000
//total3: 先将一个数转化为long
特殊情况:
long l = 12333333333L;
int i = 123;
short s = 12;
byte b = 8;
System.out.println("l + i + s + b: " + (l+i+s+b));
//最高long,结果为long
System.out.println("i + s + b: " + (i+s+b));
//最高int,结果int
System.out.println("s + b: " + (s+b));
//没有int参与,结果为int
字符串连接
“+”可能变为字符串连接符
int a = 10;
int b = 20;
System.out.println("" + a + b); //~ 1020
//遇见String类型,变为字符串连接符,直接拼接
System.out.println(a + b + ""); //~ 30
//先计算10+20=30,再拼接