Reputation: 1871
I have big code and such lines:
System.out.println(car.getName());
System.out.println(car.getName() == null);
First line print outs: null
but second line print outs false, so null == null is false?
I have also tried System.out.println(car.getName() == "null");
since getName returns String but same result
Upvotes: 3
Views: 1693
Reputation: 11
The result is "null", not null
, so your code will be:
System.out.println(car.getName().equals("null"));
Upvotes: 1
Reputation: 14053
When it comes to String you need to use the equals
method:
System.out.println("null".equals(car.getName());
if it actually returns the String "null" which is not the same as null
.
Why using equals
instead of ==
, I can't find a simpler explanation than this one:
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality.
Upvotes: 4
Reputation: 55533
If I had to guess, your code has something like this in it:
public String getName()
{
return "null";
}
So, when you run your test,
System.out.println(car.getName() == null);
It is testing the string object "null"
with the value null
, which is indeed false.
Upvotes: 1