一、类型和变量
1.类型是值的集合,以及可以对这些值执行的操作
2.基本数据类型,对象数据类型
将基本数据类型封装为对象
语言可以自动转换,但效率降低
如:
List<Integer> list = new ArrayList<Integer>();
list.add(1) ;
list.add(50);
list.add(Integer.valueOf(1)); //自动完成的操作
list.add(Integer.valueOf(50));
在编译时需要知道所有变量的类型,编译器可以推断所有表达式的类型
3.static checking中的类型转换
int a = 2; // a = 2
double a = 2; // a = 2.0 (Implicit)
int a = 18.7; // ERROR
int a = (int)18.7; // a = 18
double a = 2/3; // a = 0.0 由小到大的类型是不报错的,但是会先求值才进行转换。
double a = (double)2/3; // a = 0.6666…
4.Dynamic checking
1.非法参数比如除0错误
2.超出范围的索引值
3.空指针
5.陷阱
由于基本类型的表示范围限制而与正确结果不符,是不报错的。
1.比如5/2会返回整数
2.如果int值乘法溢出了,也不报错,而是返回溢出后的错误值
3.Int a=resulOfFunction(XX); // E.g., -9
the result of Math.sqrt(a) is NaN, not a dynamic error!
二、Mutability and Immuttability
不变数据类型创建完后,值不可修改
java还提供了final 使得一旦指定引用位置,不可再次指定。
final提供了静态检查的支持。
– A final class declaration means it cannot be inherited.
– A final variable means it always contains the same value/reference
but cannot be changed;
– A final method means it cannot be overridden by subclasses;
可变数据类型的好处是节省空间