I am trying to return a toString if something is true.
I have this code:
public void printoutsailings() {
for (Sailing s:sailings) {
String hamburg = ("Hamburg");
if ((s.getDeparturePort()) == hamburg) {
System.out.println(s.toStringAdjusted());
}
}
}
However I get nothing when I run the method (when I should be getting something). I assume that I have somehow messed up the logic or not understood =,== and eq properly, I’m not too sure.
There is nothing wrong with the toString or the for loop, and I’m not getting any compiler or run time errors. It’s just that the logic is wrong.
If someone could put me right that’d be appreciated. Thanks.
You should be using
.equals()instead of==to checkStringequality. Try the following:In short,
==checks to see if two strings are the exact same reference, and.equals()checks to see if two strings look the same.It should also be said that you need to use
.equals()for checking the equality of anyObjecttype, not just strings. Only primitive types (int,double,char) should use==for equality.To compensate for the fact that the departure might be null, simply switch the condition around. It would read –
hamburg.equals(s.getDeparturePort())