aspose file tools*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strings" Watch "Strings" New topic
Author

Strings

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;
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

Joined: Jul 08, 2003
Posts: 24166
    
  30

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.


[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: http://aspose.com/file-tools
 
subject: Strings
 
Similar Threads
Displaying Data
Strange behaviour of bit shifting
garbage collection
Array Problem
Game of Life Help