2019独角兽企业重金招聘Python工程师标准>>>

1、When you declare a reference variable (i.e. an object) you are really creating a pointer to an object. Consider the following code where you declare a variable of primitive type int:

int x;
x = 10;

In this example the variable x is an int and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.

But, when you try to declare a reference type something different happens. Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but, it does not contain a primitive value. Instead it contains a pointer (because the type is Integer which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning "I am pointing at nothing".

In the second line, the new keyword is used to instantiate (or create) an object of type Integer and the pointer variable num is assigned this object. You can now reference the object using the dereferencing operator . (a dot).

The Exception that you asked about occurs when you declare a variable but did not create an object. If you attempt to dereference num BEFORE creating the object you get a NullPointerException. In the most trivial cases the compiler will catch the problem and let you know that "num may not have been initialized" but sometime you write code that does not directly create the object.

For instance you may have a method as follows:

public void doSomething(SomeObject obj){//do something to obj
}

in which case you are not creating the object obj, rather assuming that is was created before the doSomething method was called. Unfortunately it is possible to call the method like this:

doSomething(null);

in which case obj is null. If the method is intended to do something to the passed-in object, it is appropriate to throw the NullPointerException because it's a user error and the user will need that information for debugging purposes.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething could be written as:

/**@param obj An optional foo for ____. May be null, in which case
*  the result will be ____. */
public void doSomething(SomeObject obj){if(obj != null){//do something} else {//do something else}
}

Finally, http://stackoverflow.com/q/3988788/2775450

2、"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault. Silently ignoring invalid input and doing nothing in the method is extremely poor advice because it hides the problem.

3、Check if the object equals null before you invoke a method on it or try to access a variable it might have. Some times structuring your code can help avoid null pointer exception. eg when checking an input string with a constant string you should start with the constant string like here: if ("SomeString".equals(inputString)) {} //even if inputString is null no exception is thrown. So there are a bunch of things that you can do to try to be safe.

They're exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NPE. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NPE would be:

public class Example
{public static void main(String[] args){Object obj = null;obj.hashCode();}
}

On the first line inside main I'm explicitly setting the Object reference obj to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NPE because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

转载于:https://my.oschina.net/u/2009816/blog/730880

关于NullPointerException相关推荐

  1. java.lang.NullPointerException异常原因及解决

    java.lang.NullPointerException异常原因是因为创建了一个引用类型的变量却没有指向任何对象而又去通过这个引用类型变量加点的形式去访问非静态的方法及属性. 给出三种情况, 第一 ...

  2. java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean java.lang.String.equals(j

    今天切正式环境出现的空指针 记录一下 下面是错误 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean j ...

  3. java jdk 8u111_8u111-jdk-alpine在java开发中的NullPointerException错误解决方案

    问题描述 在部署一个验证码服务的容器服务时遇到了一个空指针错误,错误代码为: java.lang.NullPointerException at sun.awt.FontConfiguration.g ...

  4. 抛出一个nullpointerexception_Java 14 发布了,再也不怕 NullPointerException 了!

    推荐阅读: Java程序员danni:就一个HashMap,居然能跟面试官扯上半个小时?​zhuanlan.zhihu.com 2020年3月17日发布,Java正式发布了JDK 14 ,目前已经可以 ...

  5. NullPointerException 的处理新方式,Java14 真的太香了!

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源:锅外的大佬 1.传统的 NullPointerExcepti ...

  6. 一个NullPointerException,竟然有这么多花样!

    本文转载于公众号:肥朝 案发现场 我们先看一下给出的异常栈 java.lang.NullPointerExceptionat org.springframework.data.redis.cache. ...

  7. 绝望,上传文件失败。。遇到并解决java.lang.NullPointerException

    解决报错:java.lang.NullPointerException 解决方法:将文件的编码方式改为utf-8即可! 截图: 修改成功后: 代码: import os import json imp ...

  8. java.lang.NullPointerException空指针问题

    对于一个Android新手而言遇见空指针问题是在所难免的.比如在调试时一开程序就出现"很抱歉!'XXX'已停止运行!"这是空指针的一种表现. 为什么会出现空指针? 所谓空指针异常, ...

  9. asd.equals(s)与s.equals(asd)为什么前者可避免NullPointerException

    下图为String源码 讲上图中 if (  anObject instanceof Object)  改为if ( this instanceof Object && anObjec ...

  10. 解决非controller使用@Autowired注解注入报错为java.lang.NullPointerException问题

    解决非controller使用@Autowired注解注入报错为java.lang.NullPointerException问题 参考文章: (1)解决非controller使用@Autowired注 ...

最新文章

  1. Spring Webflux: Kotlin DSL [片断]
  2. Canvas的save和restore方法
  3. 转载 - Struts2基于XML配置方式实现对action的所有方法进行输入校验
  4. Spring 核心容器类BeanDefinitionReader
  5. gin 前端文件打包_远程URL文件批量下载打包的方法
  6. 有意思的记录-shell(持续更新)
  7. .net core2.0下Ioc容器Autofac使用
  8. c语言表达式5 gt 3 gt 1,C语言题目谁会做?
  9. 广州python平均薪资_爬取广州的python和Java薪资,为什么Python 高于Java(有代码)...
  10. 职称计算机提前考试试卷,职称计算机考试多项选择考试卷模拟考^试题
  11. JavaScript 原型总结三 函数和对象的关系
  12. LeetCode 1 两数之和 python
  13. 1.0-并发编程-进程和线程简介
  14. JDK的Proxy技术实现AOP,InvocationHandler和Proxy详解——Spring AOP(三)
  15. ffmpeg利用crop滤镜进行视频裁剪
  16. 淘宝联盟官方APi在小程序云函数中的使用教程(附案例)
  17. codeforces 337 D(树的直径性质)
  18. sublime 实现浏览器预览功能
  19. java swing 实现鼠标滑轮聚焦缩放图片
  20. 在一个字符串中找出元音字母a,e,i,o,u出现的次数

热门文章

  1. c语言以冒号分割字符串,C语言里面的冒号
  2. mysql 统计_mysql数据统计级别技巧
  3. python os模块详细_Python文件系统功能--os模块详解
  4. VS编辑器 设置智能提示
  5. 社工库365开网站公开售卖盗取的账号信息
  6. Go 指针,标识符命名规范及关键字
  7. com.sun.mail.smtp.SMTPSendFailedException: 550 Invalid User
  8. 深入理解Spring AOP思想
  9. 插入排序 - 二分插入排序
  10. Python3.X新特性之print和exec