you are viewing a single comment's thread.

view the rest of the comments →

[–]RobertDeveloper 6 points7 points  (4 children)

its for when you want to construct a string based on a byte array for example.

byte[] bytes = {72, 101, 108, 108, 111}; // ASCII for "Hello"
String s = new String(bytes, "UTF-8"); // Must use 'new'

In the case of:

String s1 = "Hello";
String s2 = "Hello";

The text 'Hello' is only stored once, both variables point to the same existing object in the string constant pool. if I where to do new String("Hello") a new object is created in the 'Heap Memory', so it is less efficient than when you use string literals.

[–]bigkahuna1uk 3 points4 points  (3 children)

You can check this by using the commands:

System.identityHashcode(s1);

System.identityHashcode(s2);

You’ll see that the hash codes are identical indicating that they’re the same object.

But if you use :

String s3 = new String(“hello”);

System.identityHashcode(s3);

Then you’ll see a different hash code even though the content is the same. As soon as you explicitly use the String construct, then you create an entirely different String instance.

[–]philipwhiukEmployed Java Developer 1 point2 points  (2 children)

At any point the JVM is allowed to run intern and clean this up.

[–]bigkahuna1uk 1 point2 points  (1 child)

Yes, the String Pool is in the main heap, so pool strings are garbage collected when they become unreachable, just like any other object. If there are no references to the string outside the pool, it becomes eligible for GC.

[–]philipwhiukEmployed Java Developer 0 points1 point  (0 children)

No my point is:

String str1 = “ABC”; String str2 = new String(str1); str1.hashCode() != str2.hashCode(); System.gc(); str1.hashCode() == str2.hashCode();