Gson isJsonObject() throws NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have the following code:
final JsonObject source = source.toJson();
final JsonElement relatedSpace = source.get("myField");
if(relatedSpace.isJsonObject()){
//do something
}
isJsonObject() does return instanceof JsonObject; according the the Gson code. instanceof should do a null check first, so I'm not sure how it's possible that my code is throwing a NullPointerException when relatedSpace is null. I can easily check for null first to fix the issue, but I'm wondering why this happens.

The . operator is executed prior to the method after it.
If the object is null it will cause a NullPointerException, regardless to the content of the method.

Because relatedSpace is set to null (before you use it) in the situation you describing here. You actually get null from the following expression -
final JsonElement relatedSpace = source.get("myField");
(That means thee is no JsonElement with associated with the key "myField")
To avoiding null you may simply just check it before using it -
if(null!=relatedSpace && relatedSpace.isJsonObject()){
//do something
}
For more on how to avoid NullPointerException you may check these nice suggestions

You are getting NPE because you are doing a method call on null reference. What you are confused about is between operator and methods in java. instanceof is an operator in java which works with null references too but the method calls on null reference is an exceptional condition and should be handled by null check.Other thing that you can do is to ditch the GSON method altogether and do a direct instance of check.

Related

Best way to check null for each part of an experssion in java [duplicate]

This question already has answers here:
Check chains of "get" calls for null
(11 answers)
Closed 1 year ago.
So I have something that looks like this:
(String) loginResponse.getGroup().getAdditionalProperties().get(something);
and each and every component of the expression could return null. I want to avoid throwing an exception and checking if null after each call doesn't look like the best way to do it:
temp= loginResponse.getGroup();
if(temp!=null){
temp= temp.getAdditionalProperties()
if(temp!=null){
temp.get(something)
}
}etc...
What's a better way to do this?
Thanks
you can use "Optional" and chain the call inside a map()
Optional.ofNullable(toto).map(A::getB).map(B::getC).orElseThrow(...)
Optional.ofNullable(toto).map(A::getB).map(B::getC).orElseGet(...)
You avoid nullPointerException by this way. It goes in the orElse... if anly element is null at any places

Best practise to handle Exception in thread "main" java.lang.NullPointerException from Bean class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Am using Bean class to get/set value for the attributes. In some cases am gettig Exception in thread "main" java.lang.NullPointerException error due to the value is null. What will be the best practice to handle null pointer exception when we get/set values from/to bean class.
Is that ternary operator is good to use or any other suggestions?
Please find the below line of code where am getting null pointer exception.
doc.setCatalog_title(sourceAsMap.get("catalog_title").toString());
The nullpointer exception basic reason is that you are calling a method or variable from null variable where with null variable I mean a variable which is currently not holding reference of any object. So, the easy way to avoid it is assign that variable a refernce on which subsequent tasks can be called
Now this can be handled in n no. of ways, out of which some basic ways are:
1) Using if condition
if(doc!=null && sourceAsMap!=null && sourceAsMap.get("catalog_title")!=null)
doc.setCatalog_title(sourceAsMap.get("catalog_title").toString());
2) Using ternary operator:
doc = null == doc ? new Document():doc;
doc.setCatalog_title(sourceAsMap!=null && sourceAsMap.get("catalog_title")!=null ? sourceAsMap.get("catalog_title").toString() : null);
Hope that helps
You can use Guava Preconditions (https://github.com/google/guava/wiki/PreconditionsExplained), as it good practice to check preconditions of your class before executing it. As you can use checkNotNull(T).
If you are expecting null in your system then instead of using a null check, use Optional class https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html,
If you are using Java 7 then you can use Optional from Guava https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

Difference between using variable first and using variable at the end when comparing object? [duplicate]

This question already has answers here:
Interview : Java Equals
(7 answers)
Closed 6 years ago.
I have seen in many places that the constant value is used first and then the variable for example ("ram").equals(a) and in many places I have seen that the variable is used first and then the constant value with which they want to compare for example a.equals("ram").
what is the difference between a.equals("ram") and ("ram").equals(a) ?
which one is better to use and why ?
The first style is safer in situations when variable a is allowed to be null, because you can skip null checking.
When you write
if (a.equals("ram")) { ... }
you must ensure that a is not null to avoid a null pointer exception. This is not necessary for
if ("ram".equals(a)) { ... }
because equals() method is required to process null arguments without throwing an exception:
For any non-null reference value x, x.equals(null) should return false.
("ram").equals(a) is better. The code will never break even if a is null.
saves us from null pointer exception.

Typecasting null in java [duplicate]

This question already has answers here:
No Exception while type casting with a null in java
(10 answers)
Closed 7 years ago.
When we are using System.out.println(null) then we get compilation error and to resolve this we typecast null like:
System.out.println((String)null)
and then it starts working fine.
My questions is how we are allowed to typecast null when we say that null is something which is not pointing to any location and thus has no value in itself.
Also if null is not pointing to any location then the object which is null will get Garbage collected then why we are using it at first place? I know it is litle bit out of the topic but it came to my mind.
I have seen few answers in below link but they mostly talk about println method functionality and implementation but I want to know about null only.
No Exception while type casting with a null in java
In Java, "null" is a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.
That's why it does not throw error you can also do this null==null

Comparing strings in an if: !string.equals("") vs !"".equals(string) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between these two conditions?
I am doing some code cleanup and NetBeans made a suggestion to change
if(!billAddress1.equals("")) to if (!"".equals(billAddress1)).
What is the difference between the two, and the advantages of using the suggested version over the readability of the original version?
billAddress1.equals("") will cause a NullPointerException if billAddress1 is null, "".equals(billAddress1) wont.
// Could cause a NullPointerException if billAddress1 is null
if(!billAddress1.equals(""))
// Will not cause a NullPointerException if billAddress1 is null
if (!"".equals(billAddress1))
!"".equals(billAddress1) will never cause an NPE, so it allows a more compact syntax by allowing to get rid of the billAddress1 == null that would otherwise be required.
The latter will not cause a Null pointer exception if the value is null.
One saves you from NPE as others have pointed out. But if you are sure it's not going to be null then the better way to check if a string is empty is to use the String.isEmpty() method, that's what the code seems to be trying to do.
The first one has a potential to cause NullPointerException.

Categories

Resources