-8

I've seen some of this answered for PHP, SQL and C++, but can't find by java. There is some convention or best practice with that?

I'm asking about null not equals vs ==

if (myString != null && myString == null)

or

if (!myString.equals(null) && myString.equals(null))
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109

3 Answers3

7

mystring == null, if mystring would actually be null it would throw an exception, because you are trying to access its equals method.

Yuri
  • 2,008
  • 17
  • 36
  • 1
    And if you don't want to care about checking null before check a string value , you can do `"astring".equals(myString)` – Hacketo May 21 '15 at 09:27
  • This answer gives good additional reasons why not to use .equals, even if OP is specifically not asking about it :) https://stackoverflow.com/a/4501084/3255525 – JimLohse Jan 04 '18 at 22:56
1

If myString is not null, myString.equals(null) is false by definition. If it is null, it will throw NullPointerException.

If you want to check whether myString is null, you have to check it by myString == null;

Zereges
  • 5,139
  • 1
  • 25
  • 49
0

if (!myString.equals(null) && myString.equals(null))

Would not work as you are attempting to call a method (.equals) on the the none-existent object myString.

Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81