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

后端 未结 12 1109
悲&欢浪女
悲&欢浪女 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 05:10

    One simple way to understand the difference is below:-

    String s ="abc";
    String s1= "abc";
    String s2=new String("abc");
    
            if(s==s1){
                System.out.println("s==s1 is true");
            }else{
                System.out.println("s==s1 is false");
            }
            if(s==s2){
                System.out.println("s==s2 is true");
            }else{
                System.out.println("s==s2 is false");
            }
    

    output is

    s==s1 is true
    s==s2 is false
    

    Thus new String() will always create a new instance.

提交回复
热议问题