English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriais Básicos de Java

Controle de fluxo do Java

Array do Java

Java Orientação a Objetos (I)

Java Orientação a Objetos (II)

Java Orientação a Objetos (III)

Tratamento de Exceções Java

Lista do Java

Java Queue (Fila)

Conjunto Map do Java

Conjunto Set do Java

Java Entrada e Saída (I/)

Reader do Java/Writer

Outros tópicos do Java

Uso e exemplo do método intern() da String no Java

Java String (String) Methods

O método intern() da String no Java retorna a representação normalizada do objeto da string.

A sintaxe do método intern() da string é:

string.intern()

Aqui, string é um objeto da classe String.

Parâmetros do método intern()

  • Sem qualquer parâmetro

Retorno do método intern()

  • Retorna a representação normalizada da string

O que é o Interning de String no Java?

A string aninhada garante que todas as strings com o mesmo conteúdo usem a mesma memória.

Suponha que tenhamos duas strings:

String str1 = "xyz";
String str2 = "xyz";

Devido a ambos os str1and str2Com o mesmo conteúdo, portanto, essas duas strings compartilharão a mesma memória. O Java insere automaticamente strings literais.

Mas, se usar a palavra-chave new para criar uma string, essas strings não compartilharão a mesma memória. Por exemplo,

class Main {
  public static void main(String[] args) {
    String str1 = new String("xyz");
    String str2 = new String("xyz");
    System.out.println(str1 == str2); // false
  }
}

A partir deste exemplo, pode-se ver que ambos os str1and str2Have the same content. However, they are not equal because they do not share the same memory.

In this case, you can manually use the intern() method to use the same memory for strings with the same content.

Example: Java String intern()

class Main {
  public static void main(String[] args) {
    String str1 = new String("xyz");
    String str2 = new String("xyz");
    //str1and str2do not share the same memory pool
    System.out.println(str1 == str2); // false
    //uses the intern() method
    //Now, str1and str2both share the same memory pool
    str1 = str1.intern();
    str2 = str2.intern();
    System.out.println(str1 == str2); // true
  }
}

As you can see, str1and str2Have the same content, but they are not equal from the beginning.

Then, we use the intern() method so that str1and str2Use the same memory pool. After using intern(), str1and str2Equal.

Java String (String) Methods