傢伙就是這兩者之間的區別。
(1)
String s = new String("hello"); // creating an object on heap then assign that object to the reference s.
(2)
String s = "hello" // did I make an object here?? Im not using the word new.
此外陣列示例
int x[] = {1, 2, 3, 4, 5}; // did I make object here?
正如一個音符時,字符串文字是一個預先定義的字符串對象的源代碼的表示。因此,使用新的關鍵字,您實際上正在製作一個現有String對象的*副本。所以你最終得到了2個String對象而不是一個。 – 2012-03-30 16:14:54
so String s =「hello」did not create a new object ??我認爲在java everthing是一個對象? – user1293258 2012-03-30 16:18:53
@ user1293258:它是一個對象,它只是一個*字符串文字*。 jvm維護一個*字符串文字池,並重用相同的對象。所以,在assiment's =「hello」'和後來比較's'到''hello''時,使用了相同的字符串 - 這是同一個對象。關於:「我認爲在java中everthing是一個對象」 - 這不是事實。 'int','boolean' [和所有其他*原始類型*]都是** not **對象。 – amit 2012-03-30 16:22:42