What is the Difference between String s1="Hello"
and String s1=new String("Hello")
in Java?
If String s1="Hello"
and String s2=new String("Hello")
, will s1 == s2
?
What is the Difference between String s1="Hello"
and String s1=new String("Hello")
in Java?
If String s1="Hello"
and String s2=new String("Hello")
, will s1 == s2
?
String myStr = "hello";
String myStr1 = "hello";
These both will evaluate to true when compared via double equals. However, they are not equal but rather both point to the same "literal string" in memory. This is NEVER how you compare contents of a String so don't let this fool you.
String myStr = new String("hello");
String myStr1 = new String("hello");
Will evaluate to false because they both reference distinct objects with distinct memory addresses.
Always always always use myStr.equals(myStr1)
when comparing String's contents for equality.
Remember ==
only compared whether they reference the same object in memory.
Coding this:
String s1 = "Hello";
Causes the JVM to intern the String literal: Every usage of the same String literal will be a reference to the same object.
Coding this:
String s2 = new String("Hello")
Will always create a new String object.
So, will s1 == s2
?
No, never.
Here is a quote from Joshua Bloch's Effective Java regarding the use of "new String()" :
As an extreme example of what not to do, consider this statement:
String s = new String("stringette"); // DON'T DO THIS!
The statement creates a new String instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor ("stringette") is itself a String instance, functionally identical to all of the objects created by the constructor. If this usage occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly. The improved version is simply the following:
String s = "stringette";
If String s1="Hello" and String s2=new String("Hello"), will s1 == s2?
Answer is: No.
Because, s1 and s2 are different object and string
is immutable. So, s1 == s2
will be false
and s1.equals(s2)
will be true
.
Your question's answer is no, please find the reason below:-
The condition, s1==s2 will compare memory locations which are now 2 different locations in memory. So it will come false.