I want 开发者_如何学JAVAto perform some action ONLY IF my string has a meaningful value. So, I tried this.
if (!myString.equals("")) {
doSomething
}
and this
if (!myString.equals(null)) {
doSomething
}
and this
if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}
and this
if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}
and this
if ( myString.length()>0) {
doSomething
}
And in all cases my program doSomething
in spite on the fact that my string IS EMPTY. It equals to null
. So, what is wrong with that?
ADDED:
I found the reason of the problem. The variable was declared as a string and, as a consequence, null
assigned to this variable was transformed to "null"
! So, if (!myString.equals("null"))
works.
if (myString != null && !myString.isEmpty()) {
// doSomething
}
As further comment, you should be aware of this term in the equals
contract:
From Object.equals(Object)
:
For any non-null reference value
x
,x.equals(null)
shouldreturn false
.
The way to compare with null
is to use x == null
and x != null
.
Moreover, x.field
and x.method()
throws NullPointerException
if x == null
.
If myString
is null
, then calling myString.equals(null)
or myString.equals("")
will fail with a NullPointerException
. You cannot call any instance methods on a null variable.
Check for null first like this:
if (myString != null && !myString.equals("")) {
//do something
}
This makes use of short-circuit evaluation to not attempt the .equals
if myString
fails the null check.
Apache commons StringUtils.isNotEmpty
is the best way to go.
If myString is in fact null, then any call to the reference will fail with a Null Pointer Exception (NPE). Since java 6, use #isEmpty instead of length check (in any case NEVER create a new empty String with the check).
if (myString != null && !myString.isEmpty()){
doSomething();
}
Incidentally if comparing with String literals as you do, would reverse the statement so as not to have to have a null check, i.e,
if ("some string to check".equals(myString)){
doSomething();
}
instead of :
if (myString != null && myString.equals("some string to check")){
doSomething();
}
WORKING !!!!
if (myString != null && !myString.isEmpty()) {
return true;
}
else {
return false;
}
Updated
For Kotlin we check if the string is null or not by following
return myString.isNullOrEmpty() // Returns `true` if this nullable String is either `null` or empty, false otherwise
return myString.isEmpty() // Returns `true` if this char sequence is empty (contains no characters), false otherwise
You need to check that the myString
object is null
:
if (myString != null) {
doSomething
}
If your string is null, calls like this should throw a NullReferenceException:
myString.equals(null)
But anyway, I think a method like this is what you want:
public static class StringUtils
{
public static bool isNullOrEmpty(String myString)
{
return myString == null || "".equals(myString);
}
}
Then in your code, you can do things like this:
if (!StringUtils.isNullOrEmpty(myString))
{
doSomething();
}
I would encourage using an existing utility, or creating your own method:
public static boolean isEmpty(String string) {
return string == null || string.length() == 0;
}
Then just use it when you need it:
if (! StringUtils.isEmpty(string)) {
// do something
}
As noted above, the || and && operators short circuit. That means as soon as they can determine their value they stop. So if (string == null) is true, the length part does not need to be evaluated, as the expression would always be true. Likewise with &&, where if the left side is false, the expression is always false and need not be evaluated further.
As an additional note, using length is generally a better idea than using .equals. The performance is slightly better (not much), and doesn't require object creation (though most compilers might optimize this out).
Try,
myString!=null && myString.length()>0
if (myString != null && myString.length() > 0) {
// your magic here
}
Incidently, if you are doing much string manipulation, there's a great Spring class with all sorts of useful methods:
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html
Every time i have to deal with strings (almost every time) I stop and wonder which way is really the fastest way to check for an empty string. Of course the string.Length == 0 check should be the fastest since Length is a property and there shouldn't be any processing other than retrieving the value of the property. But then I ask myself, why is there a String.Empty? It should be faster to check for String.Empty than for length, I tell myself. Well i finnaly decided to test it out. I coded a small Windows Console app that tells me how long it takes to do a certain check for 10 million repitions. I checked 3 different strings: a NULL string, an Empty string, and a "" string. I used 5 different methods: String.IsNullOrEmpty(), str == null, str == null || str == String.Empty, str == null || str == "", str == null || str.length == 0. Below are the results:
String.IsNullOrEmpty()
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds
str == null
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds
str == null || str == String.Empty
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds
str == null || str == ""
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds
str == null || str.length == 0
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds
According to these results, on average checking for str == null
is the fastest, but might not always yield what we're looking for. if str = String.Empty
or str = ""
, it results in false. Then you have 2 that are tied in second place: String.IsNullOrEmpty()
and str == null || str.length == 0
. Since String.IsNullOrEmpty()
looks nicer and is easier (and faster) to write I would recommend using it over the other solution.
I'd do something like this:
( myString != null && myString.length() > 0 )
? doSomething() : System.out.println("Non valid String");
- Testing for null checks whether myString contains an instance of String.
- length() returns the length and is equivalent to equals("").
- Checking if myString is null first will avoid a NullPointerException.
I been using StringUtil.isBlank(string)
It tests if a string is blank: null, emtpy, or only whitespace.
So this one is the best so far
Here is the orignal method from the docs
/**
* Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
* @param string string to test
* @return if string is blank
*/
public static boolean isBlank(String string) {
if (string == null || string.length() == 0)
return true;
int l = string.length();
for (int i = 0; i < l; i++) {
if (!StringUtil.isWhitespace(string.codePointAt(i)))
return false;
}
return true;
}
For me the best check if a string has any meaningful content in Java is this one:
string != null && !string.trim().isEmpty()
First you check if the string is null
to avoid NullPointerException
and then you trim all space characters to avoid checking strings that only have whitespaces and finally you check if the trimmed string is not empty, i.e has length 0.
This should work:
if (myString != null && !myString.equals(""))
doSomething
}
If not, then myString likely has a value that you are not expecting. Try printing it out like this:
System.out.println("+" + myString + "+");
Using the '+' symbols to surround the string will show you if there is extra whitespace in there that you're not accounting for.
if(str.isEmpty() || str==null){
do whatever you want
}
Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab. You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists. For example, there are all numbers, char, boolean etc. The normal data types or complex data types is everything else. A String is an array of chars, therefore a complex data type.
Every variable that you create is actually a pointer on the value in your memory. For example:
String s = new String("This is just a test");
the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory.
When you call System.out.println(anyObject)
, the toString()
method of that object is called. If it did not override toString
from Object, it will print the pointer.
For example:
public class Foo{
public static void main(String[] args) {
Foo f = new Foo();
System.out.println(f);
}
}
>>>>
>>>>
>>>>Foo@330bedb4
Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.
For example:
int i = 123;
i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).
Okay so lets come back to the ==
operator.
It always compares the pointer and not the content saved at the pointer's position in the memory.
Example:
String s1 = new String("Hallo");
String s2 = new String("Hallo");
System.out.println(s1 == s2);
>>>>> false
This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.
Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.
Greetings
I had this problem in android and i use this way (Work for me):
String test = null;
if(test == "null"){
// Do work
}
But in java code I use :
String test = null;
if(test == null){
// Do work
}
And :
private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug("strDate0 = " + strDate0);
String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug("strDate1 = " + strDate1);
return compareDateStrings(strDate0, strDate1);
}
private Integer compareDateStrings(String strDate0, String strDate1) {
int cmp = 0;
if (isEmpty(strDate0)) {
if (isNotEmpty(strDate1)) {
cmp = -1;
} else {
cmp = 0;
}
} else if (isEmpty(strDate1)) {
cmp = 1;
} else {
cmp = strDate0.compareTo(strDate1);
}
return cmp;
}
private boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
private boolean isNotEmpty(String str) {
return !isEmpty(str);
}
I prefer to use:
if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
// do something
}
Read StringUtils.isBlank() vs String.isEmpty().
In Android you can check this with utility method isEmpty
from TextUtils
,
public static boolean isEmpty(CharSequence str) {
return str == null || str.length() == 0;
}
isEmpty(CharSequence str)
method check both condition, for null
and length.
I always use like this:
if (mystr != null && !mystr.isEmpty()){
//DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}else {
//DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}
or you can copy this to your project:
private boolean isEmptyOrNull(String mystr){
if (mystr != null && !mystr.isEmpty()){ return true; }
else { return false; }
}
and just call it like :
boolean b = isEmptyOrNull(yourString);
it will return true if is empty or null.b=true
if is empty or null
or you can use try catch and catch when it is null.
I think that myString is not a string but an array of strings. Here is what you need to do:
String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
//Do something
}
You can check string equal to null using this:
String Test = null;
(Test+"").compareTo("null")
If the result is 0 then (Test+"") = "null".
I tried most of the examples given above for a null in an android app l was building and IT ALL FAILED. So l came up with a solution that worked anytime for me.
String test = null+"";
If(!test.equals("null"){
//go ahead string is not null
}
So simply concatenate an empty string as l did above and test against "null" and it works fine. In fact no exception is thrown
Exception may also help:
try {
//define your myString
}
catch (Exception e) {
//in that case, you may affect "" to myString
myString="";
}
If you are working in Android then you can use the simple TextUtils class. Check the following code:
if(!TextUtils.isEmpty(myString)){
//do something
}
This is simple usage of code. Answer may be repeated. But is simple to have single and simple check for you.
I'm using a function like this where I pass the get string result into it so I don't have to constantly check null and it either returns the string you passed back or empty if it's null:
public static String safeGet(String str) {
try {
if (str == null) throw new Exception();
return "" + str;
} catch (Exception e) {
return "";
}
}
You have to check with null if(str != null).
精彩评论