new String比字符串池浪費空間,為什么要用它?
對于下面程序中:ss0 = new String( "hello" );是用new()來新建對象的,存于堆中。每調(diào)用一次就會創(chuàng)建一個新的對象。當(dāng)然從節(jié)省空間的角度來講,肯定不如str="hello",有童鞋一定問,那要它有什么用?當(dāng)時設(shè)計編譯器時,為什么要設(shè)計它?馬克-to-win,那我請問你,如果在你編程序時,你還不知道字符串內(nèi)容怎么辦?這時就用到new String(String original),所以,什么都有什么的用處。
(注意不能看調(diào)試窗口里value id,eclipse的問題)
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
本章源碼
public class Test
{
public static void main(String args[]) {
String str, str1, ss0, ss1, ss2, ss3, ss4;
str = "hello";
str1 = "hello";
ss0 = new String("hello");
ss1 = new String("hello");
ss2 = new String("bye");
ss3 = new String("chi le ma");
ss4 = new String("chi le ma");
/* ==在測內(nèi)存地址是否相同,如果相同,就證明是同一個對象。== means address space is the same.str and str1 point to the same
String constant.only one place
*/
System.out.println(str1 == str);
System.out.println(ss1 == ss0);
/* equals 是看內(nèi)容是否相等,equals means as long as value is the same, it is the same.but == mean
memory address should be the same. */
System.out.println(ss1.equals("hello"));
System.out.println(str1 == "hello");
System.out.println(ss1 == "hello");
}
}
result is:
true
false
true
true
false
String class contains a static method, valueOf(). With it, you can create a String object from a value of any of the basic types
String pi = String.valueOf(3.14159);
String對象的運算符:“+”。用來連接兩個字符串。
一件需要注意的事:
你不能寫如下一段程序,系統(tǒng)會崩潰的,馬克-to-win,因為他和lang包當(dāng)中的類名String沖突,所以不要用lang包當(dāng)中的類名當(dāng)類名。因為lang包是核心包。you can not write a program like the following, the system will collapse. because it will collide with the class with the package of java.lang, so remember that don't try to use the name of class of java.lang package.
你可以用其他包當(dāng)中的類名當(dāng)類名寫程序。比如io包當(dāng)中File類。you can rewrite a class named File because it is java.io package.
class String{
String(int a)
{
System.out.println("a is"+a);
}
}
public class Test {
public static void main(String[] args) {
String d=new String(8);
}
}
輸出結(jié)果:
java.lang.NoSuchMethodError: main
Exception in thread "main"