How can I check a string against null in java? I am using
stringname.equalsignorecase(null)
but it's not w开发者_运维百科orking.
string == null
compares if the object is null. string.equals("foo")
compares the value inside of that object. string == "foo"
doesn't always work, because you're trying to see if the objects are the same, not the values they represent.
Longer answer:
If you try this, it won't work, as you've found:
String foo = null;
if (foo.equals(null)) {
// That fails every time.
}
The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.
What you probably wanted was:
String foo = null;
if (foo == null) {
// That will work.
}
The typical way to guard yourself against a null when dealing with Strings is:
String foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
// Do something here.
}
That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.
The easy way, if you're using a String literal (instead of a variable), is:
String foo = null;
...
if ("some String".equals(foo)) {
// Do something here.
}
If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.
if (StringUtils.equals(foo, bar)) {
// Do something here.
}
Another response was joking, and said you should do this:
boolean isNull = false;
try {
stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
isNull = true;
}
Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.
In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.
s == null
won't work?
Sure it works. You're missing out a vital part of the code. You just need to do like this:
boolean isNull = false;
try {
stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
isNull = true;
}
;)
Use TextUtils Method if u working in Android.
TextUtils.isEmpty(str) : Returns true if the string is null or 0-length. Parameters: str the string to be examined Returns: true if str is null or zero length
if(TextUtils.isEmpty(str)) {
// str is null or lenght is 0
}
Below is source code of this method.You can use direclty.
/**
* Returns true if the string is null or 0-length.
* @param str the string to be examined
* @return true if str is null or zero length
*/
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
If we look at the implementation of the equalsIgnoreCase method, we find this part:
if (string == null || count != string.count) {
return false;
}
So it will always return false
if the argument is null
. And this is obviously right, because the only case where it should return true
is when equalsIgnoreCase was invoked on a null String
, but
String nullString = null;
nullString.equalsIgnoreCase(null);
will definitely result in a NullPointerException.
So equals methods are not designed to test whether an object is null, just because you can't invoke them on null
.
This looks a bit strange, but...
stringName == null || "".equals(stringName)
Never had any issues doing it this way, plus it's a safer way to check while avoiding potential null point exceptions.
I'm not sure what was wrong with The MYYN's answer.
if (yourString != null) {
//do fun stuff with yourString here
}
The above null check is quite alright.
If you are trying to check if a String reference is equal (ignoring case) to another string that you know is not a null reference, then do something like this:
String x = "this is not a null reference"
if (x.equalsIgnoreCase(yourStringReferenceThatMightBeNull) ) {
//do fun stuff
}
If there is any doubt as to whether or not you have null references for both Strings you are comparing, you'll need to check for a null reference on at least one of them to avoid the possibility of a NullPointerException.
If your string having "null" value then you can use
if(null == stringName){
[code]
}
else
[Error Msg]
import it in your class
import org.apache.commons.lang.StringUtils;
then use it, they both will return true
System.out.println(StringUtils.isEmpty(""));
System.out.println(StringUtils.isEmpty(null));
You can check with String == null
This works for me
String foo = null;
if(foo == null){
System.out.println("String is null");
}
Of course user351809, stringname.equalsignorecase(null)
will throw NullPointerException.
See, you have a string object stringname
, which follows 2 possible conditions:-
stringname
has a some non-null string value (say "computer"):
Your code will work fine as it takes the form
"computer".equalsignorecase(null)
and you get the expected response asfalse
.stringname
has anull
value:
Here your code will get stuck, as
null.equalsignorecase(null)
However, seems good at first look and you may hope response astrue
,
but,null
is not an object that can execute theequalsignorecase()
method.
Hence, you get the exception due to case 2.
What I suggest you is to simply use stringname == null
Simple method:
public static boolean isBlank(String value) {
return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
With Java 7 you can use
if (Objects.equals(foo, null)) {
...
}
which will return true
if both parameters are null
.
If I understand correctly, this should do it:
if(!stringname.isEmpty())
// an if to check if stringname is not null
if(stringname.isEmpty())
// an if to check if stringname is null
I realize this was answered a long time ago, but I haven't seen this posted, so I thought I'd share what I do. This isn't particularly good for code readability, but if you're having to do a series of null checks, I like to use:
String someString = someObject.getProperty() == null ? "" : someObject.getProperty().trim();
In this example, trim is called on the string, which would throw an NPE if the string was null or spaces, but on the same line, you can check for null or blank so you don't end up with a ton of (more) difficult to format if blocks.
If the value
returned is null, use:
if(value.isEmpty());
Sometime to check null, if(value == null)
in java, it might not give true even the String is null.
The Apache StringUtils class will do this for you.
StringUtils.equals(col1, col2)
works correctly when col1, col2, or both are null.
Consider reading the entire StringUtils JavaDoc page. It has solved most if not all of the String manipulation and/or comparison problems you will encounter.
Well, the last time someone asked this silly question, the answer was:
someString.equals("null")
This "fix" only hides the bigger problem of how null
becomes "null"
in the first place, though.
There are two ways to do it..Say String==null or string.equals()..
public class IfElse {
public int ifElseTesting(String a){
//return null;
return (a== null)? 0: a.length();
}
}
public class ShortCutifElseTesting {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("enter the string please:");
String a=scanner.nextLine();
/*
if (a.equals(null)){
System.out.println("you are not correct");
}
else if(a.equals("bangladesh")){
System.out.println("you are right");
}
else
System.out.println("succesful tested");
*/
IfElse ie=new IfElse();
int result=ie.ifElseTesting(a);
System.out.println(result);
}
}
Check this example..Here is an another example of shortcut version of If Else..
精彩评论