Why new keyword not needed for String

后端 未结 4 728
耶瑟儿~
耶瑟儿~ 2020-12-07 19:18

I am new in java.

In java, String is a class.But we do not have to use new keyword to create an object of class String<

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 19:50

    String and Integer creation are different.

    String s = "Test";
    

    Here the '=' operator is overloaded for string. So is the '+' operator in "some"+"things". Where as,

    Integer i = 2;
    

    Until Java 5.0 this is compile time error; you cant assign primitive to its wrapper. But from Java 5.0 this is called auto-boxing where primitives are auto promoted to their wrappers wherever required.

    String h1 = "hi";
    

    will be different from

    String h2 = new String("hi");
    

    The reason is that the JVM maintains a string table for all string literals. so there will be an entry in the table for "hi" , say its address is 1000.

    But when you explicitly create a string object, new object will be created, say its address is 2000. Now the new object will point to the entry in the string table which is 1000.

    Hence when you say

    h1 == h2
    

    it compares

    1000 == 2000
    

    So it is false

提交回复
热议问题