英文:
What is the difference of null position placedin front and at back
问题
在Java中,以下两行代码有什么区别,或者甚至第二行代码根本不存在:
if (name != null){}
if (null != name){}
实际的代码可能类似于这样:
if ( null != name && !StringUtils.isEmpty(name) )
顺便说一下,我已经测试过这段代码,它是有效的。
英文:
In java, what is the difference between this 2 lines of code, or the second line of code don't even exist
if (name != null){}
if (null != name){}
the real code is something like this
if ( null != name&& !StringUtils.isEmpty(name) )
by the way, I have tested this code and it works
答案1
得分: 1
你的两行代码中没有任何区别,因为两者都执行了有效的空值检查。主要问题是如果你做了这样的操作:
if (myString.isEmpty() && (myString != null)) {...}
如果myString为null,这会抛出NullPointerException,因为你在执行空值检查之前对变量进行了解引用操作。最好改成:
if ((myString != null) && myString.isEmpty()) {...}
&&
运算符执行布尔与测试,并且会短路,如果左侧的测试为false,则不会执行右侧的测试。
英文:
There is no difference between your two top lines of code as both do a valid null check. The main issue is if you did something like this:
if (myString.isEmpty() && (myString != null)) {...}
This would throw a NullPointerException if myString is null since you're dereferencing the variable before doing the null check. Better to do instead:
if ((myString != null) && myString.isEmpty()) {...}
The &&
operator does a boolean AND test, and will short circuit, will end and not do the right sided test if the test on the left is false.
答案2
得分: 1
没有区别,!= 是一个逻辑运算符,用于检查确保两者不相等,所以它不关心哪一边是什么。例如:
String a = "a";
if(a != null)
{
System.out.println("它们不相等");
}
if(null != a)
{
System.out.println("它们不相等");
}
返回
它们不相等
它们不相等
英文:
There is no difference, != is a Logical Operator, and is checking to make sure they are not equivalent, so it doesn't matter which side things are on. For example:
String a = "a";
if(a != null)
{
System.out.println("they are not equal");
}
if(null != a)
{
System.out.println("they are not equal");
}
returns
they are not equal
they are not equal
答案3
得分: -2
区别在于你不能将任何内容分配给NULL。
如果你写错了,漏掉了一个感叹号符号,写成了
if (name != null) {}
你可能会错误地写成
if (name = null) {}
从而将null值赋给了变量name。
阅读这个链接:
https://knowthecode.io/yoda-conditions-yoda-not-yoda
英文:
Difference is in that you cannot assign to NULL anything.
If you would make typo and miss a ! sign within
if (name != null) {}
You could possibly make
if (name = null) {}
And by that assign null value to name
Read this
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论