• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== operator

 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi again,

I know that the "==" operator chacks for two memory references being equal .
Now in the case of Strings if i make a String object as:


Then a String object would be created and a string literal will be placed in the memory pool .
Now if i create another String object as :


Now if a match is found in the pool then it's reference is directed to that literal in the memory pool.

Now my question is that why would something like this would hold false:

 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think we have an article on the Ranch, and there are lots of old threads, like this one, which has a link in the second post to that article. If that helps, all well; if it doesn't help, ask again
 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i saw the thread but the problem is that it is returning false and not true .

String s = new String("ranch");
String s1 = new String("ranch") ;
System.out.printf(s==s1)

or something like

out.println(s=="ranch");

it should return true but it returns false

 
Henry Wong
author
Marshal
Pie
Posts: 21022
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
budsy remo wrote:i saw the thread but the problem is that it is returning false and not true .

String s = new String("ranch");
String s1 = new String("ranch") ;
System.out.printf(s==s1)

or something like

out.println(s=="ranch");

it should return true but it returns false



In the first case, you explicitly created two new strings. The JVM will honor that request, so you get two objects.

In the second case, you explicitly created a new string (actually one that you created earlier). The JVM will honor that request, so it should be different than the one created earlier for the string literals.

Henry
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have found the article from the old thread I quoted: here it is It has an example very similar to yours in.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic