How do you use Strings and string pool with a simple code example?

Strings in Java are objects that represent a sequence of characters. They are immutable, meaning once a String is created, it cannot be changed. Java has a special memory area known as the 'String Pool' that is used to store String literals. When you create a String literal, the JVM checks the String Pool first to see if an identical String already exists; if so, it reuses that String. If not, it creates a new String object in the pool.

Java, Strings, String Pool, String Literal, Immutable, JVM, Memory Management

This example demonstrates how Strings and the String Pool work in Java, showing how memory is efficiently managed through String interning.

// Java Example of String and String Pool public class StringExample { public static void main(String[] args) { String str1 = "Hello"; // created in String Pool String str2 = "Hello"; // reuses str1 from String Pool String str3 = new String("Hello"); // created outside String Pool System.out.println(str1 == str2); // true (same reference) System.out.println(str1 == str3); // false (different references) } }

Java Strings String Pool String Literal Immutable JVM Memory Management