Home  >  Article  >  Java  >  Why Can You Create Strings in Java Without the "new" Keyword?

Why Can You Create Strings in Java Without the "new" Keyword?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 21:51:03511browse

Why Can You Create Strings in Java Without the

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:

  • Performance: By using a single instance for each unique string, the JVM allocates less memory and performs fewer object creations.
  • Memory Savings: Interning ensures that only a single instance exists for each distinct string, reducing the memory footprint.
  • Equality Checking: Using "==" for string literals is valid because it checks for physical equality, which is guaranteed due to interning.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn