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 check String
equality. Try the following:
if ((s.getDeparturePort()).equals(hamburg)) {
System.out.println(s.toStringAdjusted());
}
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 any Object
type, 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())
Yup, you're relying on == comparing for equality rather than identity. Change the code to:
if (s.getDeparturePort().equals("hamburg")) {
System.out.println(s.toStringAdjusted());
}
For reference types, == in Java always means "compare the two references for equality". In other words, it returns whether two references refer to the same object.
You want to check whether the two strings are equal instead - i.e. whether they contain the same sequence of characters. That's what the overridden equals
method is for.
(To give a real-world demonstration of this, I catch a number 36 bus every morning. To me those buses are equal because they take me on the same route, but I know there are several number 36 buses - I don't get on the exact same physical bus every day.)
Note that the code above will throw a NullPointerException
if s.getDeparturePort()
returns null
. There are two ways of avoiding this. First, you can use a known-to-be-non-null reference as the target of the method call:
if ("hamburg".equals(s.getDeparturePort()))
Alternatively, you can perform an explicit nullity check:
String port = s.getDeparturePort();
if (port != null && port.equals("hamburg"))
Or you can leave it to throw an exception, if that's the most appropriate behaviour (i.e. if you really don't expect getDeparturePort()
to return null, and want to blow up if you get such bad data rather than continuing and possibly propagating the problem).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With