==和equals的比較
阿新 • • 發佈:2017-12-12
col str 新的 als 一個 bsp println span static
字符串只要new,就會產生一個新的地址 == :比較的是地址 str1,str2存儲在常量池中,內存優化,是同一個字符串
equals :比較的是內容,只要內容一樣結果就為true
1 package myeclipseFiles2; 2 3 public class String1 { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 String str1="hello"; 8 String str2="hello";9 String str3="Hello"; 10 11 String str4=new String("hello"); 12 String str5=new String("hello"); 13 //字符串只要new,就會產生一個新的地址 14 //==比較的是地址 str1,str2存儲在常量池中,內存優化,是同一個字符串 15 System.out.println(str1==str3);//false 16 System.out.println(str1==str2);//true 17 System.out.println(str1==str4);//false 18 System.out.println(str4==str5);//false 19 System.out.println(str1==str3);//false 20 //equals比較的是內容,只要內容一樣結果就為true 21 System.out.println(str1.equals(str4));//true 22 System.out.println(str1.equals(str3));//false 23 2425 } 26 27 }
1 package myeclipseFiles2; 2 3 public class String1 { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 String str1="Hello"; 8 String str4=new String("hello"); 9 str4="Hello";//重新賦值後,原來的str4 new出來的新地址被垃圾回收站回收成為空指針 10 System.out.println(str1==str4);//true 11 } 12 13 }
==和equals的比較