Processing - Weird behavior in IF statement

52 Views Asked by At

I have this code.

if(infoDisplay.readChar() == SOH) {
  waitingForReturn = false;
  println("Got here 9");
  String inStr = infoDisplay.readStringUntil(EOT);
  inStr = inStr.substring(0,inStr.length()-1);
  println("Got here 10");
  print(inStr);
  println(" - Length: " + inStr.length());
  print(heartbeat);
  println(" - Length: " + heartbeat.length());
  if(inStr == heartbeat) {
    println("Got here 11");
    return true;
  } else {            
    println("Got here 12");//Retry
    return false;
  }
} else {
      return false;
}

And my console output looks like this

Got here 9
Got here 10
HEARTBEAT - Length: 9
HEARTBEAT - Length: 9
Got here 12

What is wrong here? The two variables prints out identical and with the same length?

1

There are 1 best solutions below

3
Gabriel Marinello On BEST ANSWER

With java Strings, you have to use .equals() for equality. What you are doing here is comparing their memory address and seeing if they are the same.

So your if statement should be if (inStr.equals(heartbeat)) {