-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))
8
  • Here is the answer I think: stackoverflow.com/questions/4501061/… Commented May 21, 2015 at 9:18
  • it's about null not equals vs == Commented May 21, 2015 at 9:18
  • 1
    It is the answer for your null. Equals will throw a NullPointerException in your case. Commented May 21, 2015 at 9:19
  • if myString == null, myString.equals(null) throw null pointer .. Commented May 21, 2015 at 9:19
  • Because if it's null, it's like writing null.equals(null). Commented May 21, 2015 at 9:22

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

And if you don't want to care about checking null before check a string value , you can do "astring".equals(myString)
This answer gives good additional reasons why not to use .equals, even if OP is specifically not asking about it :) stackoverflow.com/a/4501084/3255525
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;

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.