简体   繁体   English

为什么会发生java.lang.NullPointerException?

[英]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 首先我不是Java方面的专家,所以我的问题可能很愚蠢。如果我输错了,请原谅。这是来自OCJP MCQ。我编写了以下代码

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 输出:线程“主”中的异常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; 1.是否在语句b=a+x;之前将Integer aint b初始化为0 b=a+x; is executed 被执行

2. Why it is throwing NullPointerException. 2.为什么抛出NullPointerException。

Your response will be greatly appreciated!! 您的回应将不胜感激!!

All object references are initialised to null in Java. 在Java中,所有对象引用均初始化为null So that means that the property Integer a will be null because it has not been initialised. 因此,这意味着属性Integer a将为null,因为它尚未初始化。 Therefore, that means that when b = a+x; 因此,这意味着当b = a+x; is executed, you are actually adding the variable x to the reference variable a that is null . 执行后,实际上是将变量x添加到null的引用变量a中。

To initialise the property Integer a : 要初始化属性Integer a

Integer a = new Integer(0);

You hit by the below reason specified in Docs , 您是由于“ reason specified in Docs ”中reason specified in Docs的以下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. 默认情况下,引用将初始化为null ,其中as orimirives设置为默认原始值。

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 , ie 当您尝试进行拆箱时,即

 wrapperIntegerObject.intValue();   //wrapperIntegerObject is null

null+any number you will get NullPointerException. null +任何数字,您将获得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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM