i am new to java thats y i am asking like this please try to help me
i had written the code like this:
String str = new String("hai");
String str1 = new String("hai);
if(str == str1)
System.out.println("equal");
else
System.out.println("not equal");
in main().
then it geve me the output not equl.
then i changed the first two statements as
String str = "hai";
String str1 = "hai";
and remaining code is same.
then i got the output as equal.
so i got a doubt that whether creating String objects using new operator and with out using new operator are same or not.
That's why you should use .equals() to compare Strings usually.
.equals() will tell you whether the two strings have the same contents, which is normally what you want.
== will compare string instances, which is normally not what you want, and it can be effected by things like the constant pool.
Yes, jverd thats right,
when we compare two string by == operator then the ref. are compared and
new String assign a new object.
but when we compare two String with "equals" then it compare the value of string object.
String str1=new String("newstring");
String str2=new String("newstring");
str1.equals(str2);
return true
or you can simple compare
str1.equals("newstring");
or
"newstring".euals(str1);
there some more functions like toUpperCase() and toLowerCase() and IgnoreCase()
try to use it in string comparision
with regards,
hemjyo