Java String Immutability and Using same string value to create a new string

前端 未结 4 738
醉酒成梦
醉酒成梦 2021-01-19 14:46

I know that the title of the question is not very clear, sorry about that, did not know how to put it up. I have a very basic java implementation question which I want to fo

4条回答
  •  失恋的感觉
    2021-01-19 15:10

    String that you put in quotes in you source files "like that" are compile-time constants and in case their contents match they are represented by a single entry in a constant pool inside your class's byte-code representation and thus represent a single String object at run-time.

    String name = new String("Sambhav");
    String myName= new String("Sambhav");
    

    Those are different Objects explicitly, a new String Object will created for each call, though it could reuse char array of the underlying string (the one you provide in constructor). This happens due to new keyword that envisages Java to create a new object. And that is why name != myName in that case, even though name.equals(myName)

提交回复
热议问题