• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString() problem

 
salvador rcn
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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"?
 
dav mccartney
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Carlos Failde
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== 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:

System.out.println((str.equals("test)); // outputs true
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
salvador rcn
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, i changed the code and tested according to your suggestions. its working now.thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic