wood burning stoves*
The moose likes Java in General and the fly likes == operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "== operator" Watch "== operator" New topic
Author

== operator

budsy remo
Ranch Hand

Joined: Sep 20, 2008
Posts: 103
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

Joined: Oct 13, 2005
Posts: 38057
    
  22
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

Joined: Sep 20, 2008
Posts: 103
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
Sheriff

Joined: Sep 28, 2004
Posts: 18545
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
I have found the article from the old thread I quoted: here it is It has an example very similar to yours in.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: == operator
 
Similar Threads
Stack Variables and GC
String confusion
Difference between String
Question to Kathy - from your book
How many objects will be created in the string pool?