What is the difference between null
, 0
and nothing
?
I cannot find a question addressing all three of these.
For example:
If I am getting input from a string
and parsing it to int
.
return Integer.parseInt(sc.nextLine());
Or if I am asking if a string != ""
, or a is not nothing
I am confused about which to use when and why.
I am confused about which one to use when validating data.
"Null"
in Java , the object reference is not pointing to any object, it is null."Nothing"
, Java has nothing called "Nothing""0"
means that .the string object exists with a value of "0"""
means an empty String ,i.e the String Object exists with value """nothing" means nothing in Java.
0 means an integer value greater than -1 and less than 1.
"Null" means if any Object Reference points nowhere in the memory, then it's called "Null" reference.
Null variable isn't assigned any value. The memory space (of variable) is empty or holds garbage value. while a variable is 0, the variable holds the value '0'. The memory space has value '0' stored in it.
NULL basically means no value, or unknown,NULL value could be either empty, meaningless, or not even initialized. For eg when we say, Employee bonus is null, it means the person is not getting any bonus or not eligible for bonus.now in case if value is 0 its mean employee getting bonus but currently bonus is zero.
The best approach to check String objects in Java is using org.apache.commons.lang.StringUtils.
If you do not want to use
StringUtils
, you might want to check thatsc.nextList()
is not null (!= null
) first of all, if it is not null then you can check that is different from "" (!= ""
).There isn't a "nothing" in Java. There is a
null
reference, meaning that a variable refers to no object, so it is a kind of nothing, but there isn't the concept ofundefined
as it is in Javascript.Also, please note that a
String
comparison should be done usingequals
, not!=
or==
, sostring.equals(otherString)
.The
0
value is the default value that anint
gets when declared as an instance variable.0 is a number, you use it to check if a numeric value (int, short, float, double, etc.) is the number 0.
null
is the value of a reference that points nowhere, you use it to make sure a reference does indeed reference something.nothing
is not part of Java.The closest thing for nothing (for: no information at all) is the
void
declaration of a method. It states that the method returns literally nothing.Note that 0,
null
and the empty string""
are values and thus contain information.For example, 0 is the answer to "What is 5 subtracted from 5?" (among others).
null
is the negative response to "Does this thing point to an object?".""
" could be the answer to "What is the longest sequenc of 'X's in your name?", unless your name is "Xanthippe".