Prashant Shilimkar
Prashant Shilimkar

Reputation: 8820

why java.lang.NullPointerException is occured?

Firstly i am not expert in Java.So my question(s) may be silly.Please forgive if i mistaken.This is from OCJP MCQ.I have written following code

public class Test{
Integer a;
int b;

public Test(Integer x) {
    b = a+x;
    System.out.println(""+b);
}

public static void main(String... str)
{
    new Test(new Integer("10"));
}}

Output: Exception in thread "main" java.lang.NullPointerException

I have following question in my mind,

1. Does Integer a and int b are initialized to 0 before statement b=a+x; is executed

2. Why it is throwing NullPointerException.

Your response will be greatly appreciated!!

Upvotes: 1

Views: 570

Answers (3)

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

null+any number you will get NullPointerException.

to illustrate try the below code.

  static Integer a;
  public static void main(String[] ar) {
       System.out.println(a);
       System.out.println(a+10);
  }

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

You hit by the below reason specified in Docs,

Calling the instance method of a null object.

By default reference will be initialized to null, Where as orimirives set to default primitive values.

Data Type   Default Value (for fields)
byte    0
short   0
int 0
long    0L
float   0.0f
double  0.0d
char    '\u0000'
**String (or any object)    null** //Integer is Object, int is not
boolean false

When you try to do Unboxing , i.e

 wrapperIntegerObject.intValue();   //wrapperIntegerObject is null

Upvotes: 1

blackpanther
blackpanther

Reputation: 11486

All object references are initialised to null in Java. So that means that the property Integer a will be null because it has not been initialised. Therefore, that means that when b = a+x; is executed, you are actually adding the variable x to the reference variable a that is null.

To initialise the property Integer a:

Integer a = new Integer(0);

Upvotes: 3

Related Questions