This question already has an answer here:
- How do I compare strings in Java? 23 answers
Currently i am working with String manipulation and while doing demo i have found some different behaviour.
Below is my code.
public class HelloWorld{
public static void main(String []args){
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
String strArray[] = {"Hello","Hello"};
String strArray1[] = new String[] {"Hello","Hello"};
System.out.println("str1==str2:: "+(str1==str2));
System.out.println("str1==str3:: "+(str1==str3));
System.out.println("strArray[0]==strArray[1]:: "+(strArray[0]==strArray[1]));
System.out.println("str1==strArray[1]:: "+(str1==strArray[1]));
System.out.println("strArray1[0]==strArray1[1]:: "+(strArray1[0]==strArray1[1]));
System.out.println("str1==strArray1[1]:: "+(str1==strArray1[1]));
System.out.println("args[0]==args[1]:: "+(args[0]==args[1]));
}
}
And out put of above code is. I am running code passing command line arguments.
java HelloWorld Hello Hello
str1==str2:: true
str1==str3:: false
strArray[0]==strArray[1]:: true
str1==strArray[1]:: true
strArray1[0]==strArray1[1]:: true
str1==strArray1[1]:: true
args[0]==args[1]:: false
Here i have two queries.
if i compare reference of String str1==str3 then it will return false because str3 is created using new String so that will not reside in String pool, So how str1==strArray1[1] return true??
strArray[0]==strArray[1] will return true, strArray1[0]==strArray1[1] also return true then why command line argument args[0]==args[1] return false??
Please guide.
Don't check references if all you want to compare is the content. That's why the
String
class provides theequals()
method in the first place. The former tests for reference equality, the latter for value equality.The way strings are handled internally has changed in the past, and may well change in the future. Using reference equality is relying on implementation details that you shouldn't really be relying on.
The whole point of encapsulation is to allow things to change under the covers without affecting client code. You should follow the "rules" so that you won't get bitten.
If you really want to understand how it works, you should read the Java Language Specification, available here. That's the standard for the language and anything not explicitly stated there is an implementation detail that should be irrelevant.
String strArray1[] = new String[] {"Hello","Hello"};
creates a new String array with a reference to the same string"hello"
inside the array*.args[0]==args[1]
returnsfalse
, because they are 2 different instances (not added to the String pool), they are likenew String()
. You can easily test this using :So, arguments passed to
main()
are NOT added to the String constants pool.