-3

String str = "ABC";

String str2 = new String("ABC");

In both the methods if i am looking for hashcode it is giving same hashcode

Devdutta Goyal
  • 985
  • 2
  • 11
  • 27
  • There is never a reason to write `new String("ABC")`. Java is not C++. The [documentation](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/String.html#%3Cinit%3E%28java.lang.String%29) even says, “use of this constructor is unnecessary since Strings are immutable.” – VGR Jan 24 '20 at 13:11

2 Answers2

1

I saw the explanation in the Toptal questions: https://www.toptal.com/java/interview-questions

"In general, String s = "Test" is more efficient to use than String s = new String("Test").

In the case of String s = "Test", a String with the value “Test” will be created in the String pool. If another String with the same value is then created (e.g., String s2 = "Test"), it will reference this same object in the String pool.

However, if you use String s = new String("Test"), in addition to creating a String with the value “Test” in the String pool, that String object will then be passed to the constructor of the String Object (i.e., new String("Test")) and will create another String object (not in the String pool) with that value. Each such call will therefore create an additional String object (e.g., String s2 = new String("Test") would create an addition String object, rather than just reusing the same String object from the String pool)."

0

Both expression gives you String object, but there is subtle difference between them. When you create String object using new() operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. "Java", it may return an existing object from String pool (a cache of String object , which is now moved to heap space in recent Java release), if it's already exists. Otherwise it will create a new string object and put in string pool for future re-use.

Thivya Thogesan
  • 206
  • 2
  • 12