A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Dev_Lzf 中级黑马   /  2013-4-4 15:11  /  1459 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

12. public static void giveMeSomthing(String thing) {
13.   if (thing == null | thing.length() == 0) {
14.     System.out.println("hey! nope!");
15.   } else {
16.     System.out.println("good! get it!");
17.   }
18. }

运行 giveMeSomthing(null)方法时会抛出一个nullpointexption??为什么呢?

评分

参与人数 1技术分 +1 收起 理由
黄玉昆 + 1 鼓励鼓励

查看全部评分

7 个回复

倒序浏览
因为它无法调用它的方法length()方法。
回复 使用道具 举报
哦,这样啊,谢了
回复 使用道具 举报
更改如下:
public static void giveMeSomthing(String thing) {
                if (thing == null || thing.length() == 0) {
                        System.out.println("hey! nope!");
                } else {
                        System.out.println("good! get it!");
                }
}

当判断thing == 0时,会抛出java.lang.NullPointerException异常。
因为当thing=null时,该字符串还没有在内存中创建对象,更未分空间配大小。
回复 使用道具 举报
黑马_位志国 发表于 2013-4-4 15:54
更改如下:
public static void giveMeSomthing(String thing) {
                if (thing == null || thing.length() = ...

你改后的代码时对的, 原因是, 你现在用的双||, 因为如果你想在传递的是null, 那么 当程序执行到thing==null时,
为true, 那么程序就不会执行后面的thing.length()了, 所以这样就不会报错, 而你之前的程序会报错是因为你用的单单|, 不管thing==null是否为true, 你后面的thing.length()都会执行, 而null, 是不可以调用length()方法的
回复 使用道具 举报
张权 发表于 2013-4-4 16:07
你改后的代码时对的, 原因是, 你现在用的双||, 因为如果你想在传递的是null, 那么 当程序执行到thing==nu ...

晕, 没注意, 才发现原来是你在回答问题, 还以为是你问的问题呢!!{:3_46:}
回复 使用道具 举报
黑马_位志国 发表于 2013-4-4 15:54
更改如下:
public static void giveMeSomthing(String thing) {
                if (thing == null || thing.length() = ...

嗯,用短路“与”是可以的。
回复 使用道具 举报
如果仍有问题,请继续追问,如果问题已解决,请将分类改为已解决,谢谢
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马