where do actual parameters in java store [duplicat

2020-02-16 02:39发布

问题:

This question already has answers here:
Closed 6 years ago.

If I pass a String literal to some metohd as:

String s=new String("stack");
String s2=s.concat("overflow");

where string "overflow" will be stored.

one of my friends arguing that it is created in String constant pool and I'm opposing him.

please let me know

Thanks in advance.

回答1:

All String literals go in the constant pool. The End. In this case, two constants, "stack" and "overflow", go into the pool. A new String is created that holds the same value as the "stack" in the pool, and then another String is created by concatenating the "overflow" from the constant pool to it.

Excerpt from javap -c -verbose Test:

Constant pool:
   #1 = Methodref          #10.#19        //  java/lang/Object."<init>":()V
   #2 = Class              #20            //  java/lang/String
   #3 = String             #21            //  stack
   #4 = Methodref          #2.#22         //  java/lang/String."<init>":(Ljava/lang/String;)V
   #5 = String             #23            //  overflow
   #6 = Methodref          #2.#24         //  java/lang/String.concat:(Ljava/lang/String;)Ljava/lang/String;


回答2:

This question is certainly undecidable, yet you can find out how a certain combination of java compiler and JVM does it.

As far as I can see, nothing could stop one from writing a java compiler that, when it sees a string constant, emits byte code to create that string in the heap in some way as long as the rules stated in the JLS concerning string literals are still maintained. For example, String.intern could maintain a global Map, and the compiler could compile a String literal like follows:

create a char array of the desired size
put character at index 0
put character at index 1
...
put character at index (length-1)
construct the actual string object
pass the String just created to String.intern and leave result on the stack

Actually, one could have a pre-processor changing all string constants to

(extra.HeapString.createString(new char[] { ... }))

and have createString create a String instance in such a way that the rules for String literals hold. And you couldn't write a program that could detect if it was compiled from the original source or from the preprocessed one (except through reflection on extra.HeapString).



回答3:

The string stack will be in the heap, the string overflow is in the constant pool, the third string as the result of concatenation stackoverflow in the constant pool.