what is the advantage of string object as compared to string literal

后端 未结 6 1961
你的背包
你的背包 2021-01-02 16:59

i want to know where to use string object(in which scenario in my java code). ok i understood the diff btwn string literal and string object, but i want to know that since

6条回答
  •  清酒与你
    2021-01-02 17:43

    Contrary to your question, there is a DISADVANTAGE of using a String object compared to String literal.

    When you declare a String literal, String s = "foo", the compiler will check for an existing "foo" object on the heap and assign 's' to already existing "foo".

    However, if you create a String object, String s = new String("foo"), an entirely new object will be created on the heap (even if there is already an existing "foo"). Strings being immutable this is totally unnecessary.

    Here is good reference: http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

提交回复
热议问题