Home > Java > javaTutorial > body text

In Java, the implementation of string

王林
Release: 2023-08-27 15:09:11
forward
690 people have browsed it

In Java, the implementation of string

String pooling is a process in which a single copy of each distinct string value is stored. Otherwise, strings are immutable. This way the strings can contain the same data and share the same memory. In this way, the memory required will be greatly reduced.

When the 'intern' function is called:

  • It checks for equality between two strings - i.e. whether the string object exists in the string constant pool ( SCP).

  • If available, the string will be obtained from the pool and returned. Otherwise, a new string object is created and added to the pool. A reference to the string object is also returned.

  • For two strings 'a' and 'b', if and only if a.equals(b) returns true, a.intern() == b.intern( ) is true.

Let’s look at an example:

Example

Demonstration

public class Demo{
   public static void main(String[] args){
      String s1 = new String("Its");
      String s2 = s1.concat("sample");
      String s3 = s2.intern();
      System.out.println("Checking equality of object 2 and 3 :");
      System.out.println(s2 == s3);
      String s4 = "Its a sample";
      System.out.println("Checking equality of object 3 and 4 :");
      System.out.println(s3 == s4);
   }
}
Copy after login

Output

Checking equality of object 2 and 3 :
true
Checking equality of object 3 and 4 :
false
Copy after login

A file named The Demo class contains the main function. Three instances of String objects are defined here, where the second string is the concatenation of the first string with different values. The third string is calling the ' intern ' function on the second string. These strings are compared using the '==' operator and the results are displayed on the console.

The above is the detailed content of In Java, the implementation of string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!