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

后端 未结 6 1963
你的背包
你的背包 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:20

    String a = "ABC";
    String b = new String("ABC");
    String c = "ABC";
    
    a == b // false
    a == c // true
    
    a.equals(b) // true
    a.equals(c) // true
    

    The point is that a & c point to the same "ABC" object (JVM magic). Using "new String" creates a new object each time. IMO, using string object is a disadvantage, not an advantage. However, as another poster said, string object is useful for converting byte[], char[], StringBuffer - if you need to do that.

提交回复
热议问题