Java String pool and type casting

前端 未结 2 966
暗喜
暗喜 2021-02-14 07:21

My question is in regard to the way Java handles String literals. It\'s quite clear from the Java Language Specs (JLS) that String literals are being implicitly interned - in ot

相关标签:
2条回答
  • 2021-02-14 07:54

    Seems like because you reference an object here final String stringObject = (String) object;, this is no longer a 'compile-time' constant, but a 'run-time' constant. The first example from here eludes to it with the part:

    String s = "lo";
    String str7 = "Hel"+ s;  
    String str8 = "He" + "llo"; 
    System.out.println("str7 is computed at runtime.");     
    System.out.println("str8 is created by using string constant expression.");    
    System.out.println("    str7 == str8 is " + (str7 == str8));  
    System.out.println("    str7.equals(str8) is " + str7.equals(str8));
    

    The string str7 is computed at runtime, because it references another string that is not a literal, so by that logic I assume despite that face that you make stringObject final, it still references an object, so cannot be computed at compile time.

    And from the java lang spec here, it states:

    "The string concatenation operator + (§15.18.1) implicitly creates a new String object when the result is not a compile-time constant expression (§15.28). "

    I cannot find any examples where a cast can be used, except, for this terrible, terrible example:

    System.out.println(hello == "hel" + ( String ) "lo");
    

    Which hardly has any logical use, but maybe the part about a string cast was included because of the above case.

    0 讨论(0)
  • 2021-02-14 07:59

    Casting to Object is not allowed in a compile time constant expression. The only casts permitted are to String and primitives. JLS (Java SE 7 edition) section 15.28:

    > - Casts to primitive types and casts to type String

    (There's actually a second reason. object isn't final so cannot possibly by considered a constant variable. "A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable." -- section 4.12.4.)

    0 讨论(0)
提交回复
热议问题