Strings: Objects without the "new" Keyword
Java strings are indeed objects, yet they are unique in that they can be created without the "new" keyword. This raises the question: why?
Initially, strings may appear to be created like other objects:
Object obj = new Object();
However, strings are not initialized in this manner:
String str = "Hello World";
Interning of String Literals
To understand this discrepancy, we need to delve into the concept of string interning. Interning means that every occurrence of a specific string literal (e.g., "abcd") refers to a single instance of that string, rather than creating a new instance each time.
In Java, strings declared with double quotes are treated as literals and are automatically interned. This means that:
String a = "abcd"; String b = "abcd";
will result in:
a == b; // True
String Creation with "new"
Although interning is enabled for string literals, you can still create strings using the "new" keyword:
String a = new String("abcd"); String b = new String("abcd");
However, in this case, it is possible to have:
a == b; // False
Benefits of Interning
Interning string literals provides several benefits:
Note: It's always recommended to use the .equals() method for comparing strings, even for interned strings, since it checks for content equality.
The above is the detailed content of Why Can You Create Strings in Java Without the "new" Keyword?. For more information, please follow other related articles on the PHP Chinese website!