-4

There are many answers and blogs which say that the correct way to check for null or empty string in Java is as below

if(str != null && !str.isEmpty())

But then many answers say

if(str == null)

is a wrong way to check for null value of string as in this check we see if the two objects occupy the same space in memory. I understand this statement, but if this is the case then even the check done using != also should not be a right way to check for null or not . Please help me understand this scenario.

Sourabh
  • 119
  • 1
  • 8
  • 1
    *"While checking if a string is null in Java if (str == null ) is not right"* References? – m0skit0 Dec 07 '16 at 12:45
  • 2
    *But then many answers say `if(str == null)` is a wrong way to check for null value of string as in this check we see if the two objects occupy the same space in memory.* - {{citation needed}} –  Dec 07 '16 at 12:45
  • I suggest you to check the difference between object _reference_ and object _content_. – m0skit0 Dec 07 '16 at 12:46
  • 1
    `str == null` is a completely valid way to check whether the reference `str` is pointing to an actual object or not. `str.isEmpty()` is a completely valid method to check if a `str` object (presumably of type `String`) is empty or not, *if* you're sure it's not `null`. Since `&&` is short-circuit, `if(str != null && !str.isEmpty())` is a completely valid way to do both at once. –  Dec 07 '16 at 12:47

1 Answers1

0

As the comments already point out, checking if a String reference (or any object for that matter) is null is nor wrong neither a bad habit.

I think you're confusing 2 concepts: object reference and object content. null is an empty reference, so you can always check if an object reference (e.g. variable, constant, parameter, etc...) is empty or not using == since you're comparing the references, not the contents. On the other hand, to compare 2 strings (their memory contents, not their memory addresses) you should use equals and not ==. This is because equals compares the content of the objects (actually it's not that simple since it depends on its implementation and/or overrides, but let's forget about that for now) and not the object references.

m0skit0
  • 25,268
  • 11
  • 79
  • 127