空指针异常理解

来源:互联网 发布:oracle数据库中文注释 编辑:程序博客网 时间:2024/05/22 10:54

只要明白了,什么是空指针异常,就知道怎么解决了?

在java中,更确切的说,应该是空引用异常,也就是一个对象,你没有给他分配内存,就开始使用这个对象,比如调用这个对象的方法,这时候,就会报空指针异常了。

怎么解决呢?很简单,不是没有分配内存吗,给他分配内存就行了。
怎么分配内存呢?也简单,初始化这个对象,这个对象分配了内存了。
如何初始化?你懂的...

知其所以然:NullPointerException 官方说明文档

/**

  • Thrown when an application attempts to use null in a
  • case where an object is required. These include:
    • Calling the instance method of a null object.
    • Accessing or modifying the field of a null object.
    • Taking the length of null as if it were an array.
    • Accessing or modifying the slots of null as if it
    • were an array.
    • Throwing null as if it were a Throwable
    • value.

    Applications should throw instances of this class to indicate other illegal uses of thenull object. * @author unascribed @version 1.20, 11/17/05 @since JDK1.0 */
    原创粉丝点击