String Literal Vs String Object in Java

There are two ways to represent strings: string literals and string objects. Here's an explanation of the differences between them:

String Literal

  1. A string literal is a sequence of characters enclosed in double quotes (e.g., "Hello, World!").
  2. When you create a string literal, Java automatically creates a String object that represents that literal.
  3. String literals are stored in a separate area of memory called the "string pool" or "string constant pool."
  4. If you create multiple string literals with the same content, they will reference the same object in the string pool.
  5. String literals are immutable, meaning their values cannot be changed once they are created.
String literal1 = "Hello"; String literal2 = "Hello"; System.out.println(literal1 == literal2); // true

String Object

  1. A string object is created explicitly using the new keyword followed by the String class constructor (e.g., new String("Hello, World!")).
  2. When you create a string object, Java creates a new instance of the String class, even if the content is the same as an existing string literal.
  3. String objects are stored in the heap memory, and each object has its own memory space.
  4. Unlike string literals, string objects created with the new keyword are not automatically interned or stored in the string pool.
  5. String objects are mutable, meaning you can change their values using methods such as concat(), substring(), or replace().
String object1 = new String("Hello"); String object2 = new String("Hello"); System.out.println(object1 == object2); // false

It's important to note that while the == operator compares the references of string literals or objects, the .equals() method should be used to compare their actual contents. For example:

String literal = "Hello"; String object = new String("Hello"); System.out.println(literal.equals(object)); // true

Conclusion

It is recommended to use string literals whenever possible, as they are more efficient in terms of memory usage and can take advantage of string interning for better performance.