java 面试 —— java 基础

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lanchunhui/article/details/82290428

1. char => int

  • char 类型转换为 int 类型时,是转换为其 ascii 码或 unicode 码(比如中文)

    char ch = 'A';
    int i = ch; // (int)ch
        // i = 65;
    int ch = '香';
    int i = ch; // (int)ch
        // i = 39321;   \u9999;

2. float

  • Infinity 与 NaN

    public final class Float extends Number implements Comparable<Float> {
        public static final float POSITIVE_INFINITY = 1.0f / 0.0f;  
        public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
        public static final float NaN = 0.0f / 0.0f;
    
        public static boolean isNaN(float v) {
            return (v != v);
        }
    }
    1/0
        java.lang.ArithmeticException thrown: / by zero
        // 除 0 异常,只有在除数为 0 时才会发生;
    1.0f/0.0f == 1.0f/0.0f;
        // true;
    1.0f/0.0f == 2.0f/0.0f;
        // true;
    0.0f/0.0f == 0.0f/0.0f;
        // false;

3. String

jshell> new String() == new String()
$7 ==> false

jshell> String s = "abc";
s ==> "abc"

jshell> String s2 = new String("abc")
s2 ==> "abc"

jshell> s2 == s
$10 ==> false

jshell> s2.intern() == s
$11 ==> true
  • java String pool:字符串常量池(在堆空间)

    String str1 = “ABC”; 可能创建一个对象或者不创建对象。
    如果”ABC” 这个字符串在java String池中不存在,会在java String池中创建一个String str1= “ABC”的对象。然后把str1指向这个内存地址。之后用这种方式创建多少个值为”ABC”的字符串对象。始终只有一个内存地址被分配,之后都是String的copy。这种被称为‘字符串驻留’,所有的字符串都会在编译之后自动驻留。


    这里写图片描述

  • 源码

    @Stable
    private final byte[] value;
    
    /** Cache the hash code for the string */
    // Java的字符串的hash做了缓存,第一次才会真正算,以后都是取缓存值。
    private int hash; // Default to 0

猜你喜欢

转载自blog.csdn.net/lanchunhui/article/details/82290428