null !=str 和 str !=null 两者有什么区别? String str = "";if (null ! = str){ System.out.println("空");}if (str ! = null){ System.out.println("空");}请问两种写法有什么区别? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 null!=str 这种写法永远不会出现空指针异常 。 也是极限编程建议的写法 正规写法是应该用null != str的,但很多人的习惯是用str != null,1楼的回答是正确的 难道str != null 这样就会报空吗没啥区别楼上的习惯问题 写 str != null 没有错,但是最好养成 null != str的习惯,这个例子不会产生空指针异常,但其他的很容易产生,比如 str.equals("123"). 如果养成了好的习惯,应该写成 "123".equals.(str). 因为就算str为空,还是会返回false,但如果用前者就是空指针异常。 有一个这样的贴:有人说null != str 看起来不爽,确实有点 只是因为之前有类似str == null的代码,怕少写了个 = 出错,所以就建议写成 null == str,之后的所有类似代码都把null写在前面 str!=null 会报空指针异常 鉴证完毕 你XXX 鉴定完毕 我先上代码。。String源码public boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true : (anotherString != null) && (anotherString.count == count) &&//注意这里的写法 regionMatches(true, 0, anotherString, 0, count); }Integer源码 public static Integer getInteger(String nm, Integer val) { String v = null; try { v = System.getProperty(nm); } catch (IllegalArgumentException e) { } catch (NullPointerException e) { } if (v != null) {&&//注意这里的写法 try { return Integer.decode(v); } catch (NumberFormatException e) { } } return val; } }Struts1.2 ActionServlet全局控制器中的源码 /** * <p>Initialize the factory used to create the module configuration.</p> * @since Struts 1.2 */ protected void initModuleConfigFactory(){ String configFactory = getServletConfig().getInitParameter("configFactory"); if (configFactory != null) {//注意这里的写法 ModuleConfigFactory.setFactoryClass(configFactory); } }Hibernate3.2 SessionImpl实现类的源码public Session getSession(EntityMode entityMode) { if ( this.entityMode == entityMode ) { return this; } if ( rootSession != null ) {//注意这里的写法 rootSession.getSession( entityMode ); } errorIfClosed(); checkTransactionSynchStatus(); SessionImpl rtn = null; if ( childSessionsByEntityMode == null ) { childSessionsByEntityMode = new HashMap(); } else { rtn = (SessionImpl) childSessionsByEntityMode.get( entityMode ); } if ( rtn == null ) { rtn = new SessionImpl( this, entityMode ); childSessionsByEntityMode.put( entityMode, rtn ); } return rtn; }Spring 2.0 ClassPathResource类源码 /** * This implementation returns a URL for the underlying class path resource. * @see java.lang.ClassLoader#getResource(String) * @see java.lang.Class#getResource(String) */ @Override public URL getURL() throws IOException { URL url; if (this.clazz != null) {//注意这里的写法 url = this.clazz.getResource(this.path); } else { url = this.classLoader.getResource(this.path); } if (url == null) { throw new FileNotFoundException( getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } 可以这么说: 1,有异常发生。。 2,null != str这种写法更正规或更好 以上两个观点纯属扯淡~~~~~----------------------------------------------------结论:1,建议学Java(无论是新手还是老手)多看看基础或源码。 2,参照高手修改自己不好的习惯。 3,先自己研究,不要不懂就问。 4,用好开源的优势。 拜托不要说 null != str 要比 str != null 好了,没有区别的。不过是两个指令:mov eax, dword ptr[a]cmp eax, dword ptr[b]谁先 mov 进寄存器都没有关系,反正如果相等的话,eax 中将会是 0,否则不是0。人家建议使用 null != str 没有特别的理由,无非是在 C 语言中可以写出这样的语句而语法上是有效的,而容易被人看错: if(str = null) ...而在 java 中,这是无效的语法,所以也不会被人看错,不用管它。 学习了,一直没有用 null ! = str 这样的写法. 晚辈看着也没有什么区别呀! 如果用了object的方法 去比较的话null放在前面才有用 直接拿对象去比较 没有区别吧 当 str 为null时null != str 不会报错str != null 会报错 (不能拿着null 值去比较) 你只声明不new str!=null看看会不会报空指针异常null != str不会还说别人XXX 为什么不new呢? 你看见我下面给的源码了么? 哥啊,我这中题目看过不知道多少次了,你们不觉得很无聊的东西吗?null != str 与str != null有区别吗?除了写法不同外,我看不出来有什么区别。有人说前者是防止出现空指针,你试一下null != null会不会出现空指针,连它产生的原因都不知道,就在那说的跟真的一样~~~郁闷死了~~~ 当 str 为null时 null != str 不会报错 str != null 会报错 (不能拿着null 值去比较) 还是自己多注意一哈按规范走 扯淡 str != null 什么时候会报错啊? 你报个给我看看 还有人这么说 我X 看下面代码 package 蜗牛;public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String str=null; try { if(str!= null){//我就比了你能怎么地吧。 System.out.println("注意"); }else { System.out.println("Error"); } } catch (RuntimeException e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); }catch (Exception e) { // TODO: handle exception System.out.println(e.getMessage()); } }} //输出:Error 空指针异常 是在为null的对象 调用方法时 会抛出的异常 str !=null 是绝不会报错的 str并未调用方法比较字符串才这样写 "".equals(str); 当这样写时 str.equals("") 如果str为空就会报null 经过测试str!=null 的执行效率要比null!=str的这种写法要高的多 根据 javap 反编译的指令,后者仅比前者多了一条指令。JVM 中直接有 ifnull 指令来判断某一个对象是否为空,如果使用 null != str 的话,就无法使用到这个指令,这时 JVM 会采用 if_acmpeq 也就是比较 null 常量值引用与 str 的引用是否相同。这也仅仅是 JVM 指令上的差别,对于执行效率来说没有差别。 这个是这段代码的 JVM 指令:public class Test { public static void main(String[] args) { String str = null; System.out.println(str != null); }} 0: aconst_null 1: astore_1 2: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 5: aload_1 6: ifnull 13 9: iconst_1 10: goto 14 13: iconst_0 14: invokevirtual #3; //Method java/io/PrintStream.println:(Z)V 17: returnpublic class Test { public static void main(String[] args) { String str = null; System.out.println(null != str); }} 0: aconst_null 1: astore_1 2: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 5: aconst_null 6: aload_1 7: if_acmpeq 14 10: iconst_1 11: goto 15 14: iconst_0 15: invokevirtual #3; //Method java/io/PrintStream.println:(Z)V 18: return只是稍微有点不同而已 我也感觉没什么区别, 只要不要出现类似于:str=="abc" 这样的写法就行了 str != null这个判断绝对不会报空指针的!!楼上说会报空指针的完全是误解!只有在调用str的方法的时候才可能报空指针异常、不知道楼主熟悉C语言不,C语言里有这个写法习惯if(str == null) //可以用,但是没有防止手误if(null == str) //推荐用if(str = null) //这个就是手误将==判断写成了=赋值楼主看看我举的第3个就知道了,通常为了防止误操作,在判断的时候将常量放在前面,就是为了防止手误将判断符号写成赋值 建议使用null == str这样不会抛空指针异常 [Quote=引用 47 楼 kobebryant_ 的回复:]引用 7 楼 wupure 的回复:写 str != null 没有错,但是最好养成 null != str的习惯,这个例子不会产生空指针异常,但其他的很容易产生,比如 str.equals("123"). 如果养成了好的习惯,应该写成 "123".equals.(str). 因为就算str为空,还是会返回false,但如果用前者就是空指针异常。顶[/Quot]... 如果写成str != null ,避免不了空指针现象发生。 String str = ""; if (null ! = str){ System.out.println("空"); } if (str ! = null){ System.out.println("空"); } 你的if永远为真null是只什么也没有 而不是空字符串 没有区别,null!=str 这C++的人的习惯,对Java来说没关系的。 真艹蛋!这是c或者c++延续下来的,对于java已经是一样的啦!在c++中可以使用if (str = null){ System.out.println("空");}即在if里面可以不是boolean的值写null ! = str就是为了避免c++开发者将==写成=而在java中不存在该类问题!java的if里必须是boolean类型的 null != str不报空指针,但是也代表会吞噬错误!! 搞什么。楼主所说的这两种根本就没么区别。但是如果是调用String的方法建议将String放在方法之后。这样才是不会出现空指针异常。。 没什么区别。倒是对于"".equals(str)与str.equals("")很有区别,第二种可能会报NullPointerException 我支持,但是换个写法估计就会出错了: if(str.trim().equals("")) { //这样的写法就可能NullPointerExcetpion.. .... } if(str == null || ("").equals(str.trim())) { //这样的写法就不会有NullPointerExcetpion.. .... } 不知道CSDN傻X怎么这么多,还那么多人顶1楼的,不会的不知道自己去试验一下啊,看来在这个版块发帖的大都是学生啊,缺乏经验有不愿动手,出来了还怪大学教的不好 这年头自以为是的傻X确实多, 特别是学java的... "a".equals(str)用来防止空指针异常,我绝对赞同,但是null==str防止空指针,说不过去啊 哈哈,好玩。null!=str 这种写法永远不会出现空指针异常 。 也是极限编程建议的写法我不知道一楼的这个结论是从哪得来的?竟能得到那么多人的支持!82 个回复竟有 18 人持相同观点(含顶回复之类的回复)!!!!!!!!!!!根据编译后的 JVM 反编译指令来看 str == null 比 null == str 少一行指令,但多出来的那一行是常量,详见这个帖子的 39 和 42 楼的回复。抛开 JVM 指令层面上的差异,在源代码层面上可以完全地认为这两种写法是一样的,都不会产生什么空指针异常,跟极限编程也扯不上边。 实际上 str != null 也永远不会出现空指针异常!!= 与 == 一般只会在拆箱操作时会有可能产生 NullPointerException。比如:基本类型的包装对象与其基本类型进行比较时,如果这个包装对象为 null 的话就会抛出空指针异常(因为一个 null 值是无法转换为基本类型的),不管这个对象是写在左边,还是写在右边。Integer k = null;System.out.println(k != 5); null!=str 这种写法永远不会出现空指针异常 。赞成这个。 凡是说防止报空指针的都是错的,没有区别,为什么他们会这么说呢,因为他们看错了问题,你这是用==防止空指针错误的是将str.equals("") 写成 "".equals(str); 这才是防止空指针异常 String类型的对象作为局部变量不初始化,不给用,作为成员变量,不初始化,默认为null.谈何空指针呢? 哈,这么多人回复了,真是无语。其实这个问题很早就讨论过了。大家也不用拿出源码来,源码里面都是直接使用的 str == null 这种,也就是把null放在右边。之所以提出 null == str 这种不是因为效率怎么样,只是为了屏蔽一些低级的错误,就像楼上有人说的,就是避免你手误少写了个“=”,这样就有人说了,先在都有编译报错,写成 if(str = null){}是会提示的,但是早期编写很多使用记事本没有这些功能的,所以null == str 的写法也是有道理的,至少有些公司里面的规范都是这样要求的,就好比比较是否等于0一样,常规的是直接判断 (i == 0)但是精确的比较却不是这样一个道理,所以这个问题没有必要在这吵来吵去的。习惯所致,第二种比较顺眼,但是本人还是经常写成第二种之后再改成第一种。各人有各人的想法,人身攻击的就免开尊口吧。还有,boolea b = true;if(b = false){}编译是通过的,但是却违反了你需要比较的初衷。 str != null 是不会引起空指针一场的,但是别的类型会引起空指针的。所以null != str,只是编程习惯的问题的。 String str;if(null!=str){ System.out.println("");}eclipse直接报错了,本地变量str可能没有被初始化,所以你的理论不成立阿 如果过滤和重定向是同一个页面后,会一直死循环,应该怎么解决? ibatis 源码问题? spring问题求助org.springframework.beans.factory.CannotLoadBeanClassException: tomcat 的work目录如何清理 csdn上没有高手?????? 如何允许用户在下拉框中输入信息? 100分相送,求高手解决Spring+Hibernate的问题 用struts开发jsp项目的再次开发问题! Html文档在tomcat5.0.14中的乱码 急!!!小弟明天面试,求助大家!!! 面试题 Flex上传大文件
难道str != null 这样就会报空吗没啥区别楼上的
习惯问题
有人说null != str 看起来不爽,确实有点
鉴证完毕
鉴定完毕
String源码public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true :
(anotherString != null) && (anotherString.count == count) &&//注意这里的写法
regionMatches(true, 0, anotherString, 0, count);
}Integer源码
public static Integer getInteger(String nm, Integer val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException e) {
} catch (NullPointerException e) {
}
if (v != null) {&&//注意这里的写法 try {
return Integer.decode(v);
} catch (NumberFormatException e) {
}
}
return val;
}
}
Struts1.2 ActionServlet全局控制器中的源码 /**
* <p>Initialize the factory used to create the module configuration.</p>
* @since Struts 1.2
*/
protected void initModuleConfigFactory(){
String configFactory = getServletConfig().getInitParameter("configFactory");
if (configFactory != null) {//注意这里的写法 ModuleConfigFactory.setFactoryClass(configFactory);
}
}Hibernate3.2 SessionImpl实现类的源码public Session getSession(EntityMode entityMode) {
if ( this.entityMode == entityMode ) {
return this;
} if ( rootSession != null ) {//注意这里的写法
rootSession.getSession( entityMode );
} errorIfClosed();
checkTransactionSynchStatus(); SessionImpl rtn = null;
if ( childSessionsByEntityMode == null ) {
childSessionsByEntityMode = new HashMap();
}
else {
rtn = (SessionImpl) childSessionsByEntityMode.get( entityMode );
} if ( rtn == null ) {
rtn = new SessionImpl( this, entityMode );
childSessionsByEntityMode.put( entityMode, rtn );
} return rtn;
}Spring 2.0 ClassPathResource类源码
/**
* This implementation returns a URL for the underlying class path resource.
* @see java.lang.ClassLoader#getResource(String)
* @see java.lang.Class#getResource(String)
*/
@Override
public URL getURL() throws IOException {
URL url;
if (this.clazz != null) {//注意这里的写法
url = this.clazz.getResource(this.path);
}
else {
url = this.classLoader.getResource(this.path);
}
if (url == null) {
throw new FileNotFoundException(
getDescription() + " cannot be resolved to URL because it does not exist");
}
return url;
}
1,有异常发生。。
2,null != str这种写法更正规或更好
以上两个观点纯属扯淡~~~~~
----------------------------------------------------
结论:1,建议学Java(无论是新手还是老手)多看看基础或源码。
2,参照高手修改自己不好的习惯。
3,先自己研究,不要不懂就问。
4,用好开源的优势。
mov eax, dword ptr[a]
cmp eax, dword ptr[b]谁先 mov 进寄存器都没有关系,反正如果相等的话,eax 中将会是 0,否则不是0。人家建议使用 null != str 没有特别的理由,无非是在 C 语言中可以写出这样的语句而语法上是有效的,而容易被人看错: if(str = null) ...而在 java 中,这是无效的语法,所以也不会被人看错,不用管它。
null放在前面才有用
直接拿对象去比较 没有区别吧
你只声明不new
str!=null看看会不会报空指针异常
null != str不会
还说别人XXX
为什么不new呢?
你看见我下面给的源码了么?
还是自己多注意一哈
按规范走
str != null 什么时候会报错啊? 你报个给我看看
还有人这么说
我X 看下面代码
package 蜗牛;
public class Test { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str=null;
try {
if(str!= null){//我就比了你能怎么地吧。
System.out.println("注意");
}else {
System.out.println("Error");
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
//输出:Error
比较字符串才这样写 "".equals(str); 当这样写时 str.equals("") 如果str为空就会报null
String str = null;
System.out.println(str != null);
}
} 0: aconst_null
1: astore_1
2: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
5: aload_1
6: ifnull 13
9: iconst_1
10: goto 14
13: iconst_0
14: invokevirtual #3; //Method java/io/PrintStream.println:(Z)V
17: return
public class Test { public static void main(String[] args) {
String str = null;
System.out.println(null != str);
}
} 0: aconst_null
1: astore_1
2: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
5: aconst_null
6: aload_1
7: if_acmpeq 14
10: iconst_1
11: goto 15
14: iconst_0
15: invokevirtual #3; //Method java/io/PrintStream.println:(Z)V
18: return只是稍微有点不同而已
这个判断绝对不会报空指针的!!楼上说会报空指针的完全是误解!
只有在调用str的方法的时候才可能报空指针异常、不知道楼主熟悉C语言不,C语言里有这个写法习惯if(str == null) //可以用,但是没有防止手误
if(null == str) //推荐用
if(str = null) //这个就是手误将==判断写成了=赋值楼主看看我举的第3个就知道了,通常为了防止误操作,在判断的时候将常量放在前面,就是为了防止手误将判断符号写成赋值
null == str
这样不会抛空指针异常
引用 7 楼 wupure 的回复:
写 str != null 没有错,但是最好养成 null != str的习惯,这个例子不会产生空指针异常,但其他的很容易产生,比如 str.equals("123"). 如果养成了好的习惯,应该写成 "123".equals.(str). 因为就算str为空,还是会返回false,但如果用前者就是空指针异常。顶
[/Quot]
...
if (null ! = str){
System.out.println("空");
}
if (str ! = null){
System.out.println("空");
} 你的if永远为真
null是只什么也没有 而不是空字符串
null!=str 这C++的人的习惯,对Java来说没关系的。
在c++中可以使用
if (str = null){
System.out.println("空");
}
即在if里面可以不是boolean的值写null ! = str就是为了避免c++开发者将==写成=而在java中不存在该类问题!java的if里必须是boolean类型的
但是如果是调用String的方法建议将String放在方法之后。这样才是不会出现空指针异常。。
倒是对于"".equals(str)与str.equals("")很有区别,第二种可能会报NullPointerException
我支持,但是换个写法估计就会出错了: if(str.trim().equals("")) { //这样的写法就可能NullPointerExcetpion..
....
}
if(str == null || ("").equals(str.trim())) { //这样的写法就不会有NullPointerExcetpion..
....
}
这年头自以为是的傻X确实多, 特别是学java的...
我不知道一楼的这个结论是从哪得来的?竟能得到那么多人的支持!82 个回复竟有 18 人持相同观点(含顶回复之类的回复)!!!!!!!!!!!根据编译后的 JVM 反编译指令来看 str == null 比 null == str 少一行指令,但多出来的那一行是常量,详见这个帖子的 39 和 42 楼的回复。抛开 JVM 指令层面上的差异,在源代码层面上可以完全地认为这两种写法是一样的,都不会产生什么空指针异常,跟极限编程也扯不上边。
实际上 str != null 也永远不会出现空指针异常!!= 与 == 一般只会在拆箱操作时会有可能产生 NullPointerException。比如:基本类型的包装对象与其基本类型进行比较时,如果这个包装对象为 null 的话就会抛出空指针异常(因为一个 null 值是无法转换为基本类型的),不管这个对象是写在左边,还是写在右边。Integer k = null;
System.out.println(k != 5);
赞成这个。
防止空指针错误的是将str.equals("") 写成 "".equals(str); 这才是防止空指针异常
之所以提出 null == str 这种不是因为效率怎么样,只是为了屏蔽一些低级的错误,就像楼上有人说的,就是避免你手误少写了个“=”,这样就有人说了,先在都有编译报错,写成 if(str = null){}是会提示的,但是早期编写很多使用记事本没有这些功能的,所以null == str 的写法也是有道理的,至少有些公司里面的规范都是这样要求的,就好比比较是否等于0一样,常规的是直接判断 (i == 0)但是精确的比较却不是这样一个道理,所以这个问题没有必要在这吵来吵去的。习惯所致,第二种比较顺眼,但是本人还是经常写成第二种之后再改成第一种。各人有各人的想法,人身攻击的就免开尊口吧。还有,boolea b = true;if(b = false){}编译是通过的,但是却违反了你需要比较的初衷。
if(null!=str){
System.out.println("");
}
eclipse直接报错了,本地变量str可能没有被初始化,所以你的理论不成立阿