【面经总结】Java基础 - 数据类型

14 阅读3分钟

基本数据类型

Java 基本数据类型有几种?各占多少位?

深入理解 Java 基本数据类型:dunwu.github.io/javacore/pa…

基本数据类型共 8 种 4 类。

  1. 布尔类型

    1. boolean:8位
  2. 字符型

    1. char:16位
  3. 整数型

    1. byte:8位
    2. short:16位
    3. int:32位
    4. long:64位
  4. 浮点型

    1. float:32位
    2. double:64位

值类型和引用类型的区别

概念内存使用
值类型变量名指向具体数值声明后分配一块内存空间需要赋具体值、判断使用 == 号
引用类型变量名指向引用对象的地址不分配内存,只存储内存地址可以赋 null,判断使用 equals 方法

包装类

基本类型和包装类型的区别

  1. 包装类型可以为 null,而基本类型不可以。

    1. 包装类型可以放在 POJO 类中。
    2. 数据库的查询结果可能是 null,如果使用基本类型的话,因为要自动拆箱。会导致空指针异常。
  2. 包装类型可用于泛型,而基本类型不可以

  3. 基本类型比包装类型更高效

  4. 两个包装类型的值需要用 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 可以实现对浮点数的运算,不会造成精度丢失。

  1. 在使用 BigDecimal 构造函数时,尽量传递字符串而非浮点类型(传入的浮点值会被保留)
  2. 可采用 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));