Java Puzzle with reflection and String

前端 未结 2 2061
渐次进展
渐次进展 2020-12-30 06:05

This source outputs G\'Day Mate. How this is happening ?

public static void main(String args[]) {
    System.out.println(\"Hello World\");
}

st         


        
2条回答
  •  忘掉有多难
    2020-12-30 06:44

    As new String("Hello World") creates new Object in Heap rather than using previously created "Hello World" Object in String Constant Pool.

    So, If you write

    System.out.print(new String("Hello World").intern());

    it will show output as G'Day, Mate. because intern() method return reference id of a string instance from String Constant Pool.

提交回复
热议问题