Reusability of Strings in java?

后端 未结 4 743
野趣味
野趣味 2020-12-18 22:59
String h = \"hi\";

here we are referencing string h to string literal hi. JVM has a string literal pool to store string literals so we can reuse t

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 23:35

    Yes, to make things simpler you can think of it as picking from same address, but to be more precise variables are holding same reference which is number/objectID which JVM use while mapping to proper memory address of object (object can be moved in memory but will still have same reference).

    You can test it with code like this:

    String w1 = "word";
    String w2 = "word";
    String b = new String("word"); // explicitly created String (by `new` operator) 
                                   // won't be placed in string pool automatically
    System.out.println(w1 == w2);  // true  -> variables hold same reference
    System.out.println(w1 == b);   // false -> variable hold different references,
                                   // so they represent different objects
    b = b.intern(); // checks if pool contains this string, if not puts this string in pool, 
                    // then returns reference of string from pool and stores it in `b` variable
    System.out.println(w1 == b);   // true  -> now b holds same reference as w1
    

提交回复
热议问题