This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I get NullPointerException when validating object. I send to controller dto, and when validating it. I cant understan where is the problem because product that goes into validate method is not null, Validator code :
#Override
public void validate(Object o, Errors errors) {
Product product = (Product) o;
if (product.getTitle().isEmpty() || product.getTitle() == null) {
errors.rejectValue("title", "product.title", "Product title cant be empty");
}
if (product.getDescription().isEmpty() || product.getDescription() == null) {
errors.rejectValue("description", "product.description", "Product description cant be empty");
}
if (product.getPrice().isNaN() || product.getPrice()<=0 || product.getPrice() == null) {
errors.rejectValue("price", "product.price", "Product price is not valid");
}
if (product.getCategory()==null) {
errors.rejectValue("category", "product.category", "Product category is not valid");
}
}
and i get this
java.lang.NullPointerException
com.shop.validator.ProductValidator.validate(ProductValidator.java:27)
com.shop.controller.ProductController.createProduct(ProductController.java:82)
com.shop.controller.ProductController$$FastClassBySpringCGLIB$$c0d382c4.invoke()
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
|| evaluates from left to right. So if you say
x == null || x.somethingSomething()
and if x is null, the first condition will catch the case, and it will prevent the method call on a null reference from happening. But if you say
x.somethingSomething() || x == null
and if x is null, it tries to evaluate the method call first, and throws an exception before it gets to the null check. Java (or any other computer language I'm aware of) isn't smart enough to "figure out" to do the null check first. It trusts the order you give it.
Similarly with &&:
if (x != null && x.something())
will do the null check at the right time, but
if (x.something() && x != null)
won't.
Related
I currently have an enumlist. The enumlist gets filled at random, so there is a possibility that one has the value null. That is logical because it doesn't get filled.
The problem is further in my code I have:
if (player.Enumlist().get(CART_BLACK) > 0) {
}
Java throws a NullPointerException. Is there something I could add to the if-statement to prevent this error?
If get(CART_BLACK) may return null:
Get the value before the condition and replace it with a negative value if it's null:
Integer cartBlack = player.Enumlist().get(CART_BLACK);
if (cartBlack == null) cartBlack = -1;
if (cartBlack > 0) {
If player.Enumlist() may return null
Similar, but not quite identical:
final Enumlist list = player.Enumlist();
final int cartBlack = list == null ? -1 : list.get(CART_BLACK);
if (cartBlack > 0) {
You'll need to guard against nullity:
if(player.Enumlist().get(CART_BLACK) != null &&
player.Enumlist().get(CART_BLACK) > 0) {...}
or a more efficient version:
Integer temp = player.Enumlist().get(CART_BLACK);
if (temp != null && temp > 0){...}
if( player.Enumlist().get(CART_BLACK) != null && player.Enumlist().get(CART_BLACK) > 0) {
}
This will work because ifs are checked from left to right, and if one condition fails the rest won't be evaluated and you won't get the NPE.
Correcting the issue at the end makes the trick but it is not fine because it means that it may occur in other invocations. Besides, as a consequence, you may finish by overusing not null guards as you will never know if the null is a normal case.
So you should favor the use of Optional (Java 8 or Guava) as return rather than null to make your API clearer (it may return an empty thing so convey that) and more robust (the contained object has to be specifically unwrapped).
For example :
Optional<Integer> optValue = player.Enumlist().get(CART_BLACK);
optValue.filter(v -> v > 0)
.ifPresent( v -> ...);
You need to do Null Checking:
if (player == null || player.Enumlist () == null) {
throw new Exception("Player or Enumlist cannot be null");
}
You should also check that the Integer value is not null, but I guess that would be pretty weird if you wrote the code.
You are using get which could give you an IndexOutOfBoundsException eventually. You could check that using the size method or using streams.
If (player.Enumlist().size() > CART_BLACK && player.Enumlist().get(CART_BLACK) != null && player.Enumlist().get(CART_BLACK) > 0) {
//...
}
You may check for Null also handle the exception using try..catch block
try
{
if( player.Enumlist().get(CART_BLACK)!=null && player.Enumlist().get(CART_BLACK) > 0)
{
}
}
catch(NullPointerException)
{
//handle exception here
}
I have following checks on input json and schema. I use intelliJ and it's static code analysis is saying condition shcema != null is always true.
if (json == null && schema == null){
return;
}
if ((json == null && schema != null) || (json != null && schema == null)){
throw new InvalidRequestException("error message");
} else try {
JsonSchema jsonSchema = JsonSchemaFactory.byDefault().getJsonSchema(schema);
ProcessingReport processingReport = jsonSchema.validate(json);
...
} catch ( ... ) { ... }
Now, if i don't put in the first if condition where i am checking both objects, i might miss a use-case where its okay not to provide anything. Thats why i am using return in first if and not an exception.
What am i missing here
Your first if statement checks if json and schema are both null and then in the second if statement you check whether one of them is null, right?
Well then the second if can be simplified to:
if (json == null || schema == null){
Why? Because at this point, if we know that json is null, then schema must not be null (or else it would have returned). Similarly, if we know that schema is null, then json must not be null (for the same reason).
By the way, if you want to check whether two boolean values are "different", use the XOR operator ^:
if (json == null ^ schema == null) {
This question already has answers here:
Comparing objects never returns true
(4 answers)
Closed 5 years ago.
I was wondering how can I execute both of these exceptions in the same constructor. My program compiles fine, but it won't throw the exception for the second if statement.
public Segment(Point firstPoint, Point secondPoint) {
if(firstPoint == null || secondPoint == null)
throw new IllegalArgumentException("Cannot pass a null value");
if(firstPoint == secondPoint)
throw new IllegalArgumentException("Segment cannot be 0");
this.endPoint1 = new Point(firstPoint);
this.endPoint2 = new Point(secondPoint);
}
What do you mean by throwing two exceptions? If you make throw, than method stops. If you need to combine messages, so you can do something like this:
//Parameterized constructor
public Segment(Point firstPoint, Point secondPoint)
{
String error = "";
if(firstPoint == null || secondPoint == null) {
error = "Cannot pass a null value";
}
if(firstPoint == secondPoint) {
error = error.equals("") ?
"Segment cannot be 0" :
error + ". Segment cannot be 0"
}
if (!error.equals("")){
throw new IllegalArgumentException("Segment cannot be 0");
}
this.endPoint1 = new Point(firstPoint);
this.endPoint2 = new Point(secondPoint);
}
This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 7 years ago.
Can any Java proficient / expert suggest me what is the optimistic way of checking null reference or objects before using it to avoids NullPointerException?
In my code I've more than 100 fields and most of them are required in order to pass value in request, but I need to perform null checks every time before passing it in request to avoid NullPointerException
I have shown below a little piece of code where I'm checking for null values every time for each field (lets say of more 70 times in my one file) which looks not good, code become very ugly and unreadable. Is there any way by which we can write method and perform null object checks through it?
Basically I'm looking better, Optimistic and faster way for doing this, Any quick help is much needed.
if(amount != null && amount != "" && !amount.isEmpty())
AIMRequest.put("x_Amount", amount);
if(currency != null && currency != "" && !currency.isEmpty())
AIMRequest.put("x_Currency_Code", currency);
if(expDate != null && expDate != "" && !expDate.isEmpty())
AIMRequest.put("x_Exp_Date", expDate);
...........so on
add("x_Amount", amount);
add("x_Currency_Code", currency);
add("x_Exp_Date", expDate);
void add(String name, String value)
{
if(value!=null && !value.isEmpty())
AIMRequest.put(name, value);
}
According your if's, conditions you are comparing Strings, so make a method:
public boolean isValid(String s) {
return s != null && s != "" && !s.isEmpty();
}
If you want to compare objects with this methods change the signature public boolean isValid(Object o),
and your code will be clean as this:
if(isValid(amount))
AIMRequest.put("x_Amount", amount);
if(isValid(currency)
AIMRequest.put("x_Currency_Code", currency);
if(isValid(expDate)
AIMRequest.put("x_Exp_Date", expDate);
But if you can collect all objects in an array:
public boolean isValid(Object[] os) {
for (String s : os) {
boolean isValid = s != null && s != "" && !s.isEmpty();
if (!isValid) return false;
}
return true;
}
I am trying to write less and less code and I am trying to find a way to prevent crashes.
An example what I have encountered is:
public class MyClass
{
private User user;
public MyClass()
{
// Get user from another class
// Another thread, user can be null for couple of seconds or minutes
// Asynchronous call
user = AnotherClass.getUser();
// start method
go();
}
private void go()
{
// Method 1
// Program it is crashing if user is null
if (user.getId() == 155)
{
// TO DO
}
else
{
System.out.println("User is NOT 155 !");
}
// Method 2
// Program still crashes if user is null
if (user != null && user.getId() == 155)
{
// To do
}
else
{
System.out.println("user is not 155");
}
// Method 3
// Program wont crash, but I write much more code !
if (user != null)
{
if (user.getId() == 155)
{
// To do
}
else
{
System.out.println("User is not 155 !");
}
}
else
{
System.out.println("User is not 155 !");
}
}
}
As you can see, method 3 it's working, but I am writing much more code... What should I do?
Prefer the way Short-circuit evaluation, That is method 2.
when the first argument of the AND function evaluates to false, the overall value must be false;
if (user != null && user.getId() == 155)
{
// To do
}
else
{
System.out.println("user is not 155");
}
That is the most preferable and readable code.
Your assumtions are wrong that method2 crash and method3 works. In the above code if user != null then only user.getId() == 155 executes.
Why not use a null object pattern here, so instead of setting user to be null, set it to a special 'null' case (implementation) of the User object ?
e.g.
user = AnotherClass.getUser();
if (user == null) {
user = new NullUser();
}
(ideally AnotherClass.getUser() would do the null check internally)
In this case
user.getId()
could return a special value (-1 ?) which would never equate to a valid user id. Hence your code will always look like:
if (user.getId() == 155)
The same would apply to other methods on the User object.
It's got to be something inside the block started by this statement:
if (user != null && user.getId() == 155)
That is logically identical to method 3. When the JVM sees that user is null, it should stop evaluating that.
I will say though that I encountered something like this with JVM 1.3, so if you are using a really old JVM that may be it.