How many String object..?

前端 未结 6 1330
礼貌的吻别
礼貌的吻别 2021-01-18 13:36

Me and my friend was discussing on Strings and we stuck on this:

String str = \"ObjectOne\"+\"ObjectTwo\";

He says total three Object will

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 14:36

    String object is immutable.

        String str = "ObjectOne"+"ObjectTwo"; 
    
             is same as
    
        String str = "ObjectOneObjectTwo"; 
    

    By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

    So suppose you declare a String object:

     String myString = "Hello";
    

    Next, you want to append “Guest” to the same String. What do you do?

    myString = myString + " Guest";
    

    When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So mystring will be refering to "Hello Guest". Reference to hello is lost.

      String s1 = "hello"; //case 1 
      String s2 = "hello"; //case 2 
    

    In case 1, literal s1 is created newly and kept in the pool. But in case 2, literal s2 refer the s1, it will not create new one instead.

    if(s1 == s2) System.out.println("equal"); //Prints equal

          String s= "abc"; //initaly s refers to abc
          String s2 =s;    //s2 also refers to abc
          s=s.concat("def"); // s refers to abcdef. s no longer refers to abc.
    

    enter image description here

提交回复
热议问题