How to Compare null? - java

How do we compare null values ?
For example, I am trying to compare null by
class_name == "null"
But the code doesn't checks if the class is null.
What's wrong ?

You are comparing it to the reference of the String "null".
Remove the double quotes so you get the special null type (JLS).
You want:
class_name == null
↑

class_name == null because in your way you compare it to string not to null

if(class_name == null)
// do something;

Related

Java: Can't check the boolean for null

if a HashMap is empty and I check for .containsKey()
I get a null answer.
My Problem is that If I want to check for null I get an error message
if(containsKey == null || !containsKey){
I receive the error message
Operator '==' cannot be applied to 'boolean', 'null'
Can someone tell me why this is happening. I thought that this should work
Check that the map isn't null (not that HashMap.containsKey(T) returned null, because it didn't - it can't. It returns a boolean primitive, which can only be true or false).
if (map != null && map.containsKey(someKey)) {
// ...
}
You can use the HashMap .isEmpty() method to check if your hashmap is empty or not.
containsKey can't be null as it is the method being called. Try checking if the map itself is null.
Booleans are primitives, and primitives will never be null.
Only Object classes can be null.
Following this argument, you can do this for object class Integer:
Integer myObject = 1;
if (myObject != null){
...
}
But you cannot do this for int, which is a primitive like booleans:
int myPrimitve = 1;
if (myPrimitve == null){
...
}
Your IDE will show the error Operator == cannot be applied to int, null

Null or Not Null

I know that in Java a variable can be null or not null. So I want to ask that is there any other possibility?
String abc = null; //or a value or anything or any other thing I don't know like undefined vs
if (abc == null) {
System.out.println("IF");
} else if (abc != null) {
System.out.println("ELSE IF");
}
In that code is there any need to insert an else branch? Like this:
String abc = null; //or a value or anything
if (abc == null) {
System.out.println("IF");
} else if (abc != null) {
System.out.println("ELSE IF");
} else {
//any possibility to come here ???
}
I know that in java a variable can be null or not null.
In fact that is not correct:
int test = null; // Compilation error
if (test == null) // Compilation error
Variables whose type is a primitive type cannot be null and cannot be compared with null.
Only variables whose type is a reference type (i.e. a class type or an array type) can have null as a value.
So ı want to ask that is there any other possibility
Assuming you are talking about reference types, then No.
But that is a logical tautology. If any variable can have null as a value, then its value either is null ... or it isn't null.
And in general1, for any type T, t is a variable of type T and v is an value of type T then
(t != V) <=> !(t == v)
In English: either t has the value v ... or it doesn't.
1 - There is one exception to this. If T is float or double, and you are comparing against the NaN value, then == always gives false, even if you are testing NaN == NaN !
Java have primitives and objects.
Primitives like int can not be null (they have big brothers though like Integer wrappers which actually can).
Talking about "nullness" of objects we're speaking abount reference variables or links to them. A link can be not null if it references some object or null if it does not. That's it, period, no other case.
You don't need a IF .. ELSE IF .. ELSE construct here since there is only two possibility NULL or NOT NULL. Simple IF .. ELSE construct would suffice. Better would be to use Ternary Operator like
string str = (abc == null) ? "IF" : "ELSE IF";
System.out.println(str);
(OR)
System.out.println((abc == null) ? "IF" : "ELSE IF");
Use if..else instead of if...else if...else. You have only two possibilities.
String abc=null;
if(abc==null){
System.out.println("IF");
}else{
System.out.println("ELSE");
}

Check for empty string null?

I have a json in which userId property is coming as string "null" -
"userId":"null"
I have a method which checks whether my string is null or not -
public static boolean isEmpty(String value) {
return value == null || value.isEmpty();
}
But every time my above method returns back me as false for above userId? It should true since userId is null. Is there any other api in Guava or Apache Commons which can do this?
The value null is not equal to the String "null". null means that a given object has not been assigned a value, where the String "null" is a valid object. It contains the characters n u l l, which is a valid value for a String. You need to also check if the value is the literal string "null" in order to do what you want.
Correct Check
return value == null || value.isEmpty() || value.equals("null") ;
If you want to still maintain "null" as a valid username, then change whatever is sending the json to the following format, which should be interpreted as a literal null rather than a String with content "null"
"userId":null
"null" is not the same as null.
"null" is a string 4 characters in length of the word "null".
null (no quotes) is just that--nothing.
{"userId":"null"} equals String userId = "null" in java.
{} would equal String userId = null when unmarshalled.

How to handle null string in java

I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate.
I tried all this but that didn't work.
String COMPLETEDATE;
COMPLETEDATE = country[23];
if(country[23] == null && country[23].length() == 0)
{
// ...
}
if (COMPLETEDATE.equals("null"))
{
// ...
}
if(COMPLETEDATE== null)
{
// ...
}
if(COMPLETEDATE == null || COMPLETEDATE.equals("null"))
{
// ...
}
For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:
if("constantString".equals(COMPLETEDDATE)) {
// logic
}
But in general, your approach isn't correct.
The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.
The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.
Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.
Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".
To check null string you can use Optional in Java 8 as below:
import Optional
import java.util.Optional;
import it as above
String str= null;
Optional<String> str2 = Optional.ofNullable(str);
then use isPresent() , it will return false if str2 contains NULL otherwise true
if(str2.isPresent())
{
//If No NULL
}
else
{
//If NULL
}
reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
It is not entirely clear what you are asking, but to check if a String variable is null, use the following statement.
if(myString==null)
This checks whether the object reference is null.
The following statement, which you have written is incorrect for two reasons.
if (COMPLETEDATE.equals("null"))
{
// ...
}
1. null is a keyword in Java, "null" is just a string of text.
2. .equals() checks to see if two objects are equal according to the given method's definition of equality. Null checks should always be made using the == comparison operator, as it checks reference equality.
If a variable is null, you cannot dereference it.
That means you can not invoke methods on it.
So... The following if statement will throw a NullPointerException every time the first clause is true:
if (a == null && a.length() == 0)
In other words: if a is null, you CANNOT invoke the length method on a.

NullPointerException using HashMap

I am trying to filter this exception by checking whether the HashMap is Null using an if statement. If the HashMap is null then running a method which loads it with values however seems that the if statement is also giving an NullPointerException.
How can this be restructured?
sqldata is the Hashmap and it is being loaded elsewhere however there is a possibility that it might not have any values (as per design) in which case I am trying to check (if the HashMap is empty/null) and reload it using a code snippet below:
if (sqldata.isEmpty()||sqldata.equals(null)) {
sqldata = fileloader.dbhealthload();
}
sqldata.equals is running the method equals of sqldata. In the case that sqldata is null, it does not have any methods, so java does not find it and throws a NullPointerException. You should check it with ==:
if (sqldata == null || sqldata.isEmpty()) {
sqldata = fileloader.dbhealthload();
}
Null references have no methods. Thus, you can't test null with equals - instead, you should test it with the == operator.
Change your code to
if(sqldata == null || sqldata.isEmpty())
You should not check for null this way,
// Invokes method on null when sqldata is null. so, this shouldn't be done
if (sqldata.isEmpty()||sqldata.equals(null)) {
sqldata = fileloader.dbhealthload();
}
Instead you need to check for null like this
if(sqldata == null || sqldata.isEmpty()){
sqldata = fileloader.dbhealthload();
}
you should use:
if (sqldata == null || sqldata.isEmpty()) {
sqldata = fileloader.dbhealthload();
}
At first you should check whether sqldata is null or not . After that you should check the emptyness.
First you need to check whether sqldata is null or not then you can proceed to check whether HashMap is empty. Follow the given approach.
if (sqldata==null||sqldata.isEmpty())
{
sqldata = fileloader.dbhealthload();
}
if sqldata is null and using first sqldata.isEmpty() in if then it will throw NullPointerException.
The reason for null pointer exception might be that you HashMap is never instantiated. One way to correct this is to ensure that the HashMap is always instantiated and then restructuring the code in the following way:
if(!sqldata.isEmpty()) {
do operations ...
} else {
reload ...
}
It is recommended to use the above programming practice. However, if you do not want an enforced instantiation of the HashMap object, then you need to check that is it null or not and once you have checked that, you should proceed to check whether it is empty. The code in that case will be:
if(!(sqldata == null)) {
if(!sqldata.isEmpty()) {
do operations ...
}
} else {
reload or instantiate ...
then do operations ...
}
You may also write the other way around.
In Java null is not an object, just a void reference, so you shouldn't call .equals on variable that can be null. The only correct way is to compare it with reference comparison:
sqldata == null
Another thing is || is lazy, this means as soon as it finds first (from left to right) true value, it does not evaluate other operands. Hence a very common pattern:
sqldata == null || sqldata.isEmpty()
And you should use it. The operator && is lazy also, so things like:
sqldata != null && sqldata.doStuff()
are possible.
The same applies to any variable, for example String variable.
s == null || s.isEmpty()
When it comes to comparing strings with a literal another common pattern should be used:
"a value".equals( s )
It work's and is safe because:
in case s is null .equals can handle it, just nothing equals to null
"a value" is a string literal, so it is never null
As a guideline, don't compare strings the other way around:
s.equals("a value")
and don't use reference comparison:
s == "a value"
A string variable sometimes can point to the same object as the literal, but not always!
Generally NullPointerException throw when when you try to use a reference that points to no location in memory (null).Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerExecption.
In your code you are try to calling method isEmpty() using null reference of you HashMap object.
Always check null before checking any other condition or accessing method using object reference.
For Example :
HashMap sqldata = new HashMap();
if(sqldata!=null && sqldata.isEmpty())
{
sqldata = fileloader.dbhealthload();
}

Categories