Rumah > Java > javaTutorial > teks badan

Mengapa Rentetan Boleh Dicipta Tanpa Kata Kunci 'Baharu' di Jawa?

Susan Sarandon
Lepaskan: 2024-11-13 13:12:02
asal
967 orang telah melayarinya

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();
Salin selepas log masuk

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";
Salin selepas log masuk

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
Salin selepas log masuk

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
Salin selepas log masuk

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");
}
Salin selepas log masuk

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.

Atas ialah kandungan terperinci Mengapa Rentetan Boleh Dicipta Tanpa Kata Kunci 'Baharu' di Jawa?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan