myString prints "aString" but myString != "aString" , what's wrong here?

I am using extraPixels bluetoothDesktop Library to search for a specific bluetooth service. I can print the service's name but when checking the value in an IF statement it does not equal what it printed. What gives? Thanks for any help.

Processing 2.1.1 Windows 7

import bluetoothDesktop.*;

String targetService="Dev B";   //this is a bluetooth service provided by a arduino module
PFont font;

Bluetooth bt;
Service[] services = new Service[0];

void setup(){
  size(300,150);
  bt = new Bluetooth(this, Bluetooth.UUID_RFCOMM); // RFCOMM
  bt.start("find_service");
  bt.find();//search for devices and services, uses serviceDiscover*() functions
}

void draw(){
  background(0);
  fill(255);

  if (services!=null) {
    for (int i=0; i<services.length; i++) {
      text("the value of services["+i+"].name is "+services[i].name, 0,30);
      text("the value of targetService is        "+targetService, 0, 45);
      if(services[i].name == targetService){
        text(services[i].name +" == "+ targetService, 0, 60);
      }
      else{
        text(services[i].name +" != "+ targetService, 0, 60);
      }      
    }
  }      
}

void serviceDiscoverEvent(Service[] s) {
  services = (Service[])append(services,s[0]);
}

void serviceDiscoveryCompleteEvent(Service[] s) {
  services = (Service[])s;
}

I don't quite understand but when running this I get

the value of services[0].name is Dev B the value of targetService is Dev B Dev B != Dev B

Tagged:

Answers

  • edited February 2014 Answer ✓

    if(services[i].name == targetService)

    • In Java, the == relational operator always compare values!
    • Variables name & targetService are of String data-type.
    • Therefore, both are non-primitive variables, which store the reference value (memory address) to an object.
    • Each object has an unique address value, and thus, that comparison is always false,
      unless both happen to point to the same object!
    • Correct approach for comparing String objects is to use its method equals()!
  • RTFM, got it. Thanks, I guess I have some reading to do on Strings!

Sign In or Register to comment.