Java Strings: "String s = new String("silly");"

Solution 1:

String is a special built-in class of the language. It is for the String class only in which you should avoid saying

String s = new String("Polish");

Because the literal "Polish" is already of type String, and you're creating an extra unnecessary object. For any other class, saying

CaseInsensitiveString cis = new CaseInsensitiveString("Polish");

is the correct (and only, in this case) thing to do.

Solution 2:

I believe the main benefit of using the literal form (ie, "foo" rather than new String("foo")) is that all String literals are 'interned' by the VM. In other words it is added to a pool such that any other code that creates the same string will use the pooled String rather than creating a new instance.

To illustrate, the following code will print true for the first line, but false for the second:

System.out.println("foo" == "foo");
System.out.println(new String("bar") == new String("bar"));

Solution 3:

Strings are treated a bit specially in java, they're immutable so it's safe for them to be handled by reference counting.

If you write

String s = "Polish";
String t = "Polish";

then s and t actually refer to the same object, and s==t will return true, for "==" for objects read "is the same object" (or can, anyway, I"m not sure if this is part of the actual language spec or simply a detail of the compiler implementation-so maybe it's not safe to rely on this) .

If you write

String s = new String("Polish");
String t = new String("Polish");

then s!=t (because you've explicitly created a new string) although s.equals(t) will return true (because string adds this behavior to equals).

The thing you want to write,

CaseInsensitiveString cis = "Polish";

can't work because you're thinking that the quotations are some sort of short-circuit constructor for your object, when in fact this only works for plain old java.lang.Strings.

Solution 4:

String s1="foo";

literal will go in pool and s1 will refer.

String s2="foo";

this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal.

String s3=new String("foo");

"foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.

String s4=new String("foo");

same as s3

so System.out.println(s1==s2);// **true** due to literal comparison.

and System.out.println(s3==s4);// **false** due to object

comparison(s3 and s4 is created at different places in heap)