NullPointerException何时发生?

时间:2013-03-22 12:05:52

标签: java nullpointerexception

class  CardBoard    
{  
    Short  story = 200;  
    CardBoard  go(CardBoard cb)
    {
        cb = null;  
        return cb;  
    }  

    public static void main(String[] args)   
    {  
        CardBoard  c1 = new  CardBoard();  
        CardBoard  c2 = new  CardBoard();  
        CardBoard  c3 = c1.go(c2);   
        //  expecting  null  pointer  exception      
        c1  =  null;  
        // do stuff;  
    }   
}  

7 个答案:

答案 0 :(得分:4)

注释行中没有NPE,因为c1c2不为空。此外,在go方法中,cb变量设置为null,但这不会影响实际对象!

CardBoard  c1 = new  CardBoard();  
CardBoard  c2 = new  CardBoard();  
CardBoard  c3 = c1.go(c2);   

这些行之后的情况是:

c1 != null
c2 != null
c3 == null

那么为什么要获得NPE?

您必须了解哪些参考资料!像在调用go(c2)中一样将对象传递给方法,并且在方法中将参数设置为null 会影响原始对象实例!

就像:

object c1 = new object();
object c2 = c1;

c1 = null

结果

c1 == null
c2 != null // !!!

答案 1 :(得分:3)

我不明白你为什么期待NullPointerException 基本上你只是想说:
CardBoard c3 = null;

如果你想要NPE,你可以这样做:
CardBoard c3 = null;
c3.go(C2);

这里,c3为空,所以这将抛出一个NPE,因为你试图这样做:
null.go(...);

答案 2 :(得分:1)

  

何时出现空指针异常?

每当您调用实例方法或访问引用(指向)null的引用变量上的实例字段时。

答案 3 :(得分:1)

现在,试试:

public static void main(String[] args)   
{  
    CardBoard  c1 = new  CardBoard();  
    CardBoard  c2 = new  CardBoard();  
    CardBoard  c3 = c1.go(c2);   
    //  expecting  null  pointer  exception      
    c1  =  null;  
    c3.go(c2);
}

看看会发生什么......;) 你肯定会得到你的NPE。

(你必须实际使用空指针来获取你的异常)

答案 4 :(得分:1)

NullPointerException仅在您尝试访问任何带有指向null的引用的任何方法或变量时才会发生。

我在代码中进行了更改以获取NullPointerException:

class CardBoard {
Short story = 200;

CardBoard go(CardBoard cb) {
    cb = null;
    return cb;
}

public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);
    // expecting null pointer exception
    c1 = null;

    // If you try to call a method or access any member variable with null reference you will get the exception
    c3.story = 20; //NullPointerException will occur

    // do stuff;
}

}

答案 5 :(得分:1)

e.g。

Class Apple
{
 void applePrint()
 {
  System.out.println("Apple");
 }
}

Class Mango
{
 void mangoPrint()
 {
  System.out.println("Mango");
 }
}

假设你的代码在某处,

Apple a;

Mango m;

如果您尝试使用此变量am来访问类成员,

a.printApple(); or m.printMango();

它将抛出NPE

即。您可以为类的对象定义引用变量,但实际上并不创建它们

Apple a = new Apple(); Mango m = new Mango();

[我刚接触Java时已经做了很多]

答案 6 :(得分:1)

public static void main(String[] args)   
{  
    CardBoard  c1 = new  CardBoard();  
    CardBoard  c2 = new  CardBoard();  
    CardBoard  c3 = c1.go(c2);   // go method is returning 'null' so c3=null
    //  expecting  null  pointer  exception      
    c1  =  null;  
    c3.go(c2);  // you will get NullPointerException here.
}

当您在go()上调用c3方法时,您将获得NullPointerException

当您为分配给NullPointerException引用变量调用方法时,您将获得null