1.数据类型
代码练习01
import java.math.BigDecimal;
public class Demo3 {
public static void main(String[] args) {
//整数扩展: 进制:二进制 十 八 十六
int i = 10;
int i2 = 010;
int i3 = 0x11; //为啥是17
System.out.println(i);
System.out.println(i2);
System.out.println(i3);
//========
//浮点型扩展? 银行业务怎么表示? 钱 BigDecimal类
//float 有限 离散 舍入误差 大约 接近但不等于
// double
float f = 0.1f; //0.1
double d = 1.0/10; //0.1
System.out.println(f==d); //false
float d1 = 231231212121212f;
float d2 = d1 + 1;
System.out.println(d1 == d2); //true
//字符拓展
char c1 = 'a';
char c2 = '中';
//所有的字符本质还是数字
//编码 unicode 2字节 65536
char c3 = '\u0061';
System.out.println(c3); //a
//转义字符 \t 制表符 \n 换行
//字符串比较
String sa = new String("hello world");
String sb = new String("hello world");
System.out.println(sa == sb); //false
String sa1 = "hello world";
String sa2 = "hello world";
System.out.println(sa1 == sa2); //true
}
}
tips:
- 基础类型比较,比较值
- 对象类型比较,比较地址
2.类型转换
代码练习02
public class Demo4 {
public static void main(String[] args) {
int i = 128;
byte b = (byte) i; //内存溢出 byte -127-127
double d = i;
//强制转换 (类型)变量名 高--低
//自动转换 (类型)变量名 低--高
System.out.println(i); //128
System.out.println(b); //-128 内存溢出
System.out.println(d); //128.0
/**
* tips:
* 1 不能对布尔型进行转换
* 2 不能把对象类型转换为不相干的类型
* 3 高容量转换成低容量的时候,强制转换
* 4 转换的时候可能存在内存溢出,或者精度问题
*/
System.out.println("=========");
System.out.println((int) 23.7); //23
System.out.println((int) -45.89f); //-45
System.out.println("=========");
char c = 'a'; //97
int d1 = c+1;
System.out.println(d1); //98
System.out.println((char) d1);
}
}
代码练习03
public class Demo5 {
public static void main(String[] args) {
//操作比较大的数,注意溢出问题
//JDK7新特性,数字之间可以用下划线分割
int money = 10_0000_0000;
int years = 20;
int total = money*years; //计算溢出
long total2 = money*years; //转换之前存在问题
long total3 = money*((long)years); //先把一个数为long
System.out.println(total3);
//L ==>表示long l也可以表示l,但l可能会被当作1,所有都用大写的L
}
}
tips:
- 不能对布尔型进行转换
- 不能把对象类型转换为不相干的类型
- 高容量转换成低容量的时候,强制转换
- 转换的时候可能存在内存溢出,或者精度问题
- L ==>表示long l也可以表示l,但l可能会被当作1,所有都用大写的L