Strings: Objects without the 'New' Keyword
Strings, despite being objects in Java, can be created without the new keyword. To understand why, consider the following example:
Object obj = new Object();
This code creates an instance of the Object class using the new keyword. However, when creating a String, we use a different syntax:
String str = "Hello World";
Interned String Literals
The reason for this discrepancy lies in Java's treatment of String literals. String literals, such as "Hello World," are interned, meaning they are stored in a central String pool. Every time a String literal is encountered, Java checks the pool for an existing instance. If the String is found in the pool, Java returns a reference to that instance instead of creating a new one.
Consider the following code:
String a = "abcd"; String b = "abcd"; System.out.println(a == b); // Output: True
Since both a and b refer to the same String literal, they are physically equal (i.e., they point to the same object).
Custom Strings with 'New'
While interning is beneficial for efficiency, it is possible to create custom String instances using new. For example:
String a = new String("abcd"); String b = new String("abcd"); System.out.println(a == b); // Output: False
In this case, a and b are different String objects created using new.
Benefits of Interning
Interning String literals improves performance because it eliminates the need to create multiple instances of the same String. This is especially useful when Strings are used multiple times in a program. For example, in the following code:
for (int i = 0; i < 10; i++) { System.out.println("Next iteration"); }
The String "Next iteration" is only instantiated once due to interning, even though it is used in a loop. Without interning, each loop iteration would require a new String instance, potentially wasting memory.
以上是為什麼Java中不用「New」關鍵字也能建立字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!