2

Let's assume we have a class like this:

class Check{
    private int ammount;

public Check(){
  //Notice default empty builder
}

//Setters and getters

Now, how can we prevent NullPointerExceptions when calling on the getter for a primitive datatype?

//We cannot do this
...
if (myCheck.getAmmount() == null){
 ....
}

So, how can we prevent a NullPointerException on this cases?

chntgomez
  • 2,058
  • 3
  • 19
  • 31
  • For your reference type variables, you can avoid NullPointerException by checking prior to evaluating `if (myCheck.getAmmount() != null){ //do your job }`. Don't use mycheck.getAmmount() before testing for null. – Am_I_Helpful Aug 02 '17 at 17:10
  • I misunderstood the question at first, hope my answer helps :D – developer_hatch Aug 02 '17 at 17:16

4 Answers4

5

Primitive types can't be null. So methods returning primitive types can't return null.

Paco Abato
  • 3,920
  • 4
  • 31
  • 54
  • So, what could I expect if I do something like this: String s = String.valueOf(check.getAmount()); – chntgomez Aug 02 '17 at 17:09
  • You should do `if (check.getAmmount() != null) { String s = String.valueOf(check.getAmount()); }` - @chntgomez – Am_I_Helpful Aug 02 '17 at 17:12
  • check.getAmount() will not return null never. It will return always a primitive value. If amount is not initialized it will contain the default value 0. – Paco Abato Aug 02 '17 at 17:13
  • 1
    Thanks. I think that's what I've wanting to know. The default values on the primitive datatypes! – chntgomez Aug 02 '17 at 17:14
  • 1
    Solve it elegantly by Optional.ofNullable(check).map(c -> String.valueOf(check.getAmount())).orElse("") – ggradnig Aug 02 '17 at 17:17
0

There is no possibility of a NullPointerException in the first place from a primitive data type. There is nothing to prevent.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

Primitives like "int", "boolean", "float", "double" cannot be null. Are you referring to "Integer", "Float", "Double" instead?

pakkk
  • 289
  • 1
  • 2
  • 13
  • Let me ellaborate further, What would happen if I do something like this: String s = String.valueOf(check.getAmount()): – chntgomez Aug 02 '17 at 17:09
  • OK, in this case it depends on the method "String.valueOf" implementation. For your example (using "int" primitive) the default value of "int" is zero (0), then the "s" value will be "0" – pakkk Aug 02 '17 at 17:13
0

You must read all the question, the conclusion is not null for primitive types, they have a default value, but! don't misunderstand primitives such as

int, double, char, byte,

with classes such as

String, Integer, Double..

Those could return null to you. In that case, I recommend to read all the posible answers here What is a NullPointerException, and how do I fix it?

developer_hatch
  • 15,898
  • 3
  • 42
  • 75