why the output is "false"? if i print System.out.println(str.toString()) -> it gives "test" . so in fact , in line 1 it will check test==test....so , result should become "true"...then why the result is "false"?
I believe you would want to use something like: str.toString().equals("test") Although I am not sure off the top of my head if you can chain commands like that. As I understand it, for string comparison, using "==" would compare the reference, whereas .equals compares the value. Hope this helps!
== tests object equality: str is a reference to a string object "test" is a string literal so they are not the same object java.lang.Object)" target="_blank" rel="nofollow">equals() is what you want:
A Java String is an object. For our purposes, an object is a location in your computer's memory containing some data. You create an object using the "new" operator. Now, of course, it's possible to have two locations containing the characters t,e,s,t. In your program, there's one that Java gives you for free because you used the token "test" in your program, and there's a second one that you create with "new". These are two different objects. The operator "==" asks whether two objects are the same object -- i.e., whethere they're physically the same area of memory. In your program, we've already established that the two Strings are distinct objects, so "==" returns false. Every Java object has a method "equals" which you can call to see if two objects are "the same" in a more general sense. If you try if (str.toString().equals("test")) If your program, you'll find that it returns true, as you expected "==" to do; for Strings, equals() returns true if the two Strings contain the same characters in the same order, even if they're physically distinct. One more note: calling "toString()" on any String in Java returns the object you called it on -- i.e., calling toString() on a String does absolutely nothing, and can always be deleted without changing the meaning of the program.