Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings

 
Mitch Krah
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
continue;

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
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.
 
Mitch Krah
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic