3

Possible Duplicate:
Strings are objects in Java, so why don't we use 'new' to create them?

In Java, class objects are created like-

MyClass a=new MyClass();

then how String class objects are created like-

String a="Hello";

What does this "Hello" does to create new object?

Community
  • 1
  • 1
Naman
  • 2,363
  • 5
  • 26
  • 27

2 Answers2

4

String a = "Hello" doesn't actually create a new object. Instead, when the compiler sees a string literal like "Hello", it adds the string to the string literal pool, from which it will be loaded later.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • 3
    "If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool", so it does create an object if the String doesn't already exists in the pool. – talnicolas Dec 14 '11 at 07:48
  • 1
    @talnicolas: That happens at class load time, though, not at runtime of the bytecode in question. – Thilo Dec 14 '11 at 07:50
  • @Thilo Yeah but I think that to be clear, an object is created at some point, there's no magic here. – talnicolas Dec 14 '11 at 07:56
2

Providing a String as a literal finally makes it in the String Literal Pool of the JVM. Quoting from this article:

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.For example:

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";  
       String str2 = "Hello"; 
       System.out.print(str1 == str2);
    }
}

The result is

true

Unfortunately, when you use

String a=new String("Hello");

a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example

public class Program
{
    public static void main(String[] args)
    {
       String str1 = "Hello";  
       String str2 = new String("Hello");
       System.out.print(str1 == str2 + " ");
       System.out.print(str1.equals(str2));
    }
}

The result is

false true
dimitrisli
  • 20,895
  • 12
  • 59
  • 63