Home  >  Article  >  Java  >  Why Can Strings Be Created Without the 'New' Keyword in Java?

Why Can Strings Be Created Without the 'New' Keyword in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 13:12:021014browse

Why Can Strings Be Created Without the 'New' Keyword in Java?

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.

The above is the detailed content of Why Can Strings Be Created Without the 'New' Keyword in Java?. 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