4

What's the best way to check for not null values in java.

String query ="abcd";

query != null vs !query.equals(null).

which is better?why?

3
  • .equals defaults to == as long as it's not explicitly overridden. Commented Feb 13, 2013 at 21:07
  • @JaynathanLeung. Are you talking about String objects too? Commented Feb 13, 2013 at 21:08
  • @RohitJain are there any types of String which aren't objects? There is no primitive equivalent as far as I know... Commented Feb 13, 2013 at 21:10

4 Answers 4

26

1st one is better (and the only option), because 2nd one will throw NPE, when your value is actually null. As simple as that.

Try this out:

String str = null;
str.equals(null);  // will throw `NPE`.

So basically, the test which you wanted to perform itself triggers a NullPointerException in the 2nd case. So, it is no choice.

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

9 Comments

NPE = NullPointerException for those who don't know the acronym
@RohitJain:I did:String test = "aa"; System.out.println(test.equals(null));.Prints false
@Cratylus - now try it with String test = null; and see what happens...
@Cratylus what rohit meant was to try String s= null; s.equals(null)
@Cratylus. Why would he test for non-null if there is no possibility of null value at all? And if there is a possibility of null value, then there is NPE in 2nd case.
|
11

!str.equals(null) will

  1. always return false if it does not throw an exception, and
  2. throw an exception if str is null

The point of a null check is to make sure the reference, in this code str, actually refers to an object. If it is null, you can't call any methods on it, including equals, without throwing a NullPointerException... which the point of null checks is to avoid happening.

So !str.equals(null) causes the very problem null checks are meant to prevent and doesn't do what you think at all. Never do this.

1 Comment

+1, i made the same point about str.equals(null) would always return false, but my answer not clear about the concrete question.. :)
2

query != null better as !query.equals(null) will throw an exception when query is actually null. Also query != null is easily readable

Comments

2

query != null compares if the object is null. query.equals("something") compares the value inside of that object. string == "something". so in this case use query != null.

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.