1

I have two different programs, the one that uses int and the other Double. For the below code am getting NullpointerException

public class Solution {

    Double cost;
    void addTax(Double b)
    {
        cost+=b;
    }

    public static void main(String[] args)
    {
        new Solution().addTax(30.00);
    }
}

But for the below code that uses int isn't getting any runtime error.

public class Solution {

    int cost;

    void addTax(int b)
    {
        cost+=b;
    }

    public static void main(String[] args)
    {
        new Solution().addTax(30);
    }
}

So how does that possible? Please explain me.

hagrawal7777
  • 14,103
  • 5
  • 40
  • 70
prabhakar Reddy G
  • 1,039
  • 3
  • 12
  • 23
  • Essentially `Double` is a wrapper over `double`. Unlike `int`, which is a primitive and gets automatically initialized to 0, `Double` is an actual object which requires initialization. – npinti Oct 06 '15 at 12:16

3 Answers3

3

A primitive (such as int) gets a default value of 0, while a reference type (such as Double) gets a default value of null.

Therefore cost+=b; throws a NullPointerException in the first code snippet (since it's equivalent to cost = cost.doubleValue() + b;), while in the second snippet it is equivalent to cost = 0 + b;, which is fine.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

Double is a wrapper over double. Since Double will be set to null when your class's instance is initialized, trying to increment its value (which involves unboxing from Double to double will cause NPE.

Default value of int is 0, so no NPE Hurray :)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

In first example you're using class Double and in second one just primitive type int. My guess is that you did it by mistake and you probably you just wanted to use primitive type 'double'

Rafał Pydyniak
  • 539
  • 4
  • 11