創建String的不同方法

differet way to creat String

1,use new operator:
String s=new String("Hello");
2,a short one:
String s="Hello";
兩種方法當用於字符串時有相同的結果,但不用NEW關鍵字會創建JAVA字符串池中指向同一個字符串的指針。
字符串池是JAVA存儲資源的一種方法。
以下程序用於檢驗:
public class DifferentWayToCreatString
{
   public static void main(String args[])
   {
       String s = "Hello";
       String s2 = "Hello";
       if (s == s2)
       {
           System.out.println("Equal without new operator");
       }
       String t = new String("Hello");
       String u = new String("Hello");
       if (t == u)
       {
           System.out.println("Equal with new operator");
       }
   }
}
//輸出結果Equal without new operator
 
發佈了26 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章