2

How many string objects does the following code snippet generate in the string pool at runtime:

public class Test { public static void main(String[] args) { String string = new String("abc"); System.out.println("abc" == "def"); } } 

Does the second line generate a string object for def? Or is it ignored due to compiler optimization?

0

1 Answer 1

0

The bytecode is as follows:

 public static void main(java.lang.String[] args) { /* L7 */ 0 new 2; 3 dup; 4 ldc 3; /* "abc" */ 6 invokespecial 4; /* java.lang.String(java.lang.String autumn) */ 9 astore_1; /* autumn */ /* L8 */ 10 getstatic 5; /* java.lang.System.out */ 13 iconst_0; 14 invokevirtual 6; /* void println(boolean arg0) */ /* L10 */ 17 return; } 

So, I would say there is just one String generated. The "def" is stored in the constant pool.

Sign up to request clarification or add additional context in comments.

1 Comment

java.lang.String autumn?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.