Difference between creating String using literals vs new keyword?

Technology: java core java
AskedIn:
Topics: string
Type: theory

Note: JVM maintains a string pool (dedicated area in heap) to store all of its strings inside the memory to reuse them

  • when string is created using string literal, the compiler first looks for its existence in the string pool
    e.g. String name = “Cortana”; 
    • If the string does not exists; a new string is created
    • If the string already exists; no new string is created. Instead, the new reference (name) starts pointing to the already existing string
  • when string is created using new keyword , the compiler creates a new string even if it already exists in the string pool
    e.g. String name = new String(“Cortana”);