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.