File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strings" Watch "Strings" New topic


Mitch Krah
Ranch Hand

Joined: Sep 06, 2004
Posts: 41
I am trying to use the == comparator to determine the "value" of a string. The following code does not appear to be working:

for (i = 0; i < string.length; i++) {
if (string[i] == "A") {
count[0] += 1;

Using the deBugger I can see that string[0] = "A", but when the expression is exercised "A" == "A" results in False. Any ideas?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


Welcome to JavaRanch!

The "==" operator compares two variables (Strings or otherwise) to see if they refer to the same physical object -- the same location in RAM. The equals() method, on the other hand, is generally implemented to compare two objects for the more conventional definition of equality -- i.e., two different String objects with the same contents are equals(), but not ==. You want to use "if (string[i].equals("A"))" here.

Have a look at this and this on our "Campfire Stories" page if you don't understand what I'm talking about.

[Jess in Action][AskingGoodQuestions]
Mitch Krah
Ranch Hand

Joined: Sep 06, 2004
Posts: 41
Thank you. Worked great!

Amazing ... 1 week trying to troubleshoot this myself ... or post the question and get a solution in less than an hour.

Great return on investment.

I think I will celebrate!
I agree. Here's the link:
subject: Strings
jQuery in Action, 3rd edition