Java string pool and type conversion

My problem is the way Java handles strings It is clear from the Java language specification (JLS) that string literals are implicitly embedded - in other words, objects created in the string constant pool portion of the heap, as opposed to heap based objects created when a new string is called ("whatever you want")

What seems to be inconsistent with what JLS says. When using string connection to create a new string with a converted constant string type, it should be regarded as a JLS constant string. Obviously, the JVM is creating a new string object rather than implicitly implementing it I appreciate any explanation of this specific behavior and whether it is platform specific behavior I run on Mac OSX snow leopard

public class Test
{
    public static void main(String args[])
    {
        /*
            Create a String object on the String constant pool
            using a String literal
        */
        String hello = "hello";
        final String lo = "lo"; // this will be created in the String pool as well
        /*
            Compare the hello variable to a String constant expression,that should cause the JVM to implicitly call String.intern()
        */
        System.out.println(hello == ("hel" + lo));// This should print true
        /*
            Here we need to create a String by casting an Object back
            into a String,this will be used later to create a constant
            expression to be compared with the hello variable
        */
        Object object = "lo";
        final String stringObject = (String) object;// as per the JLS,casted String types can be used to form constant expressions
        /*
            Compare with the hello variable
        */
        System.out.println(hello == "hel" + stringObject);// This should print true,but it doesn't :(

    }
}

Solution

Conversion to an object is not allowed in compile time constant expressions The only actors allowed are string and primitive JLS (Java SE version 7) section 15.28:

> – Casts to primitive types and casts to type String

(in fact, there is a second reason. The object is not final, so it is impossible to consider a constant variable. "A variable of original 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)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>