基本数据类型
Java 基本数据类型有几种?各占多少位?
深入理解 Java 基本数据类型:dunwu.github.io/javacore/pa…
基本数据类型共 8 种 4 类。
-
布尔类型
- boolean:8位
-
字符型
- char:16位
-
整数型
- byte:8位
- short:16位
- int:32位
- long:64位
-
浮点型
- float:32位
- double:64位
值类型和引用类型的区别
概念 | 内存 | 使用 | |
---|---|---|---|
值类型 | 变量名指向具体数值 | 声明后分配一块内存空间 | 需要赋具体值、判断使用 == 号 |
引用类型 | 变量名指向引用对象的地址 | 不分配内存,只存储内存地址 | 可以赋 null,判断使用 equals 方法 |
包装类
基本类型和包装类型的区别
-
包装类型可以为 null,而基本类型不可以。
- 包装类型可以放在 POJO 类中。
- 数据库的查询结果可能是 null,如果使用基本类型的话,因为要自动拆箱。会导致空指针异常。
-
包装类型可用于泛型,而基本类型不可以
-
基本类型比包装类型更高效
-
两个包装类型的值需要用 equals 比较
Integer
int 和 Integer 有什么区别?
int 是整型数字,是基本数据类型。Java 万物皆对象,但是 int 是万物之外的。
Integer 是 int 的包装类。它具有 int 存储数据的功能,还提供了数字的基本操作。
JDK5 之后提供了自动装箱和拆箱功能,方便 int 和 Integer 之间的转换。
谈谈 Integer 的值缓存范围
JDK5 之后提供了一个静态工厂方法 valueOf
,利用了缓存机制。缓存值是 -128 ~ 127。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
BigDecimal
什么是 BigDeciml?
BigDecimal
可以实现对浮点数的运算,不会造成精度丢失。
怎么避免浮点数精度丢失问题?
使用 BigDecimal
可以实现对浮点数的运算,不会造成精度丢失。
- 在使用 BigDecimal 构造函数时,尽量传递字符串而非浮点类型(传入的浮点值会被保留)
- 可采用 BigDecimal.valueOf() 方法来构造初始化值(会将 Double 转换成字符串)
public BigDecimal(double val) {
this(val,MathContext.UNLIMITED);
}
public BigDecimal(String val) {
this(val.toCharArray(), 0, val.length());
}
public static BigDecimal valueOf(double val) {
return new BigDecimal(Double.toString(val));
}
怎么比较两个 BigDecimal 是否相等?
使用 compareTo
方法,如果相等就返回 0,如果第 1 个数比第 2 个数大则返回 1,反之返回 -1。
不要使用 equals
方法。equals()
方法不仅仅会比较值的大小还会比较精度,而 compareTo()
方法比较的时候会忽略精度。
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
System.out.println(a.compareTo(b));