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.

[586 byte] By [shahi@nandua] at [2007-11-26 22:53:27]
# 1
String literals are stored in the constant pool. So x="a"; y="a"; both return references to the same String object. The new operator always creates a new object.
jverda at 2007-7-10 12:16:45 > top of Java-index,Java Essentials,New To Java...
# 2

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.

paulcwa at 2007-7-10 12:16:45 > top of Java-index,Java Essentials,New To Java...
# 3

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

hemjyoa at 2007-7-10 12:16:45 > top of Java-index,Java Essentials,New To Java...