What is the difference between “text” and new String(“text”)?

后端 未结 12 1110
悲&欢浪女
悲&欢浪女 2020-11-21 04:42

What is the difference between these two following statements?

String s = \"text\";

String s = new String(\"text\");
12条回答
  •  误落风尘
    2020-11-21 04:56

    @Braj : i think u have mentioned the other way around. Please correct me if i am wrong

    Object creation line by line:

    String str1 = new String("java5")

       Pool- "java5" (1 Object)
    
       Heap - str1 => "java5" (1 Object)
    

    String str2 = "java5"

      pool- str2 => "java5" (1 Object)
    
      heap - str1 => "java5" (1 Object)
    

    String str3 = new String(str2)

      pool- str2 => "java5" (1 Object)
    
      heap- str1 => "java5", str3 => "java5" (2 Objects)
    

    String str4 = "java5"

      pool - str2 => str4 => "java5" (1 Object)
    
      heap - str1 => "java5", str3 => "java5" (2 Objects)
    

提交回复
热议问题