What is difference between TextUtils.isEmpty(string) and string.isEmpty?
Both do the same operation.
Is it advantageous to use TextUtils.isEmpty(string)?
Yes, TextUtils.isEmpty(string) is preferred.
For string.isEmpty(), a null string value will throw a NullPointerException
TextUtils will always return a boolean value.
In code, the former simply calls the equivalent of the other, plus a null check.
return string == null || string.length() == 0;
In class TextUtils
public static boolean isEmpty(#Nullable CharSequence str) {
if (str == null || str.length() == 0) {
return true;
} else {
return false;
}
}
checks if string length is zero and if string is null to avoid throwing NullPointerException
in class String
public boolean isEmpty() {
return count == 0;
}
checks if string length is zero only, this may result in NullPointerException if you try to use that string and it is null.
Take a look at the doc
for the String#isEmpty they specify:
boolean
isEmpty()
Returns true if, and only if, length() is 0.
and for the TextUtils.isEmpty the documentation explains:
public static boolean isEmpty (CharSequence str)
Returns true if the string is null or 0-length.
so the main difference is that using the TextUtils.isEmpty, you dont care or dont need to check if the string is null referenced or not,
in the other case yes.
TextUtils.isEmpty() is better in Android SDK because of inner null check, so you don't need to check string for null before checking its emptiness yourself.
But with Kotlin, you can use String?.isEmpty() and String?.isNotEmpty() instead of TextUtils.isEmpty() and !TextUtils.isEmpty(), it will be more reader friendly
So I think it is preferred to use String?.isEmpty() in Kotlin and TextUtils.isEmpty() in Android Java SDK
String?.isNullOrEmpty
might be what you are looking for
Related
Is there a utility method in Java which converts Boolean into boolean and automatically handles null reference to Boolean as false?
How about:
boolean x = Boolean.TRUE.equals(value);
? That's a single expression, which will only evaluate to true if value is non-null and a true-representing Boolean reference.
On java 8 you can do:
static boolean getPrimitive(Boolean value) {
return Optional.ofNullable(value).orElse(false);
}
You can also do:
static boolean getPrimitive(Boolean value) {
return Boolean.parseBoolean("" + value);
}
Are you looking for a ready-made utility ? Then I think Commons-Lang BooleanUtils is the answer. It has a method
toBoolean(Boolean bool).
I don't know whether it exists or not. I'd write a one liner like:
public static boolean getPrimitiveBoolean(Boolean bool) {
return bool == null ? false : bool.booleanValue();
}
If you're golfing, an explicit null check followed by automatic unboxing is shorter than the canonical answer.
boolean b=o!=null&&o; // For golfing purposes only, don't use in production code
This would be a method you could write that would do the trick. This would return false if the Boolean is null.
public static boolean toBooleanDefaultIfNull(Boolean bool) {
if (bool == null) return false;
return bool.booleanValue();
}
I can't check whether a string is empty or not coming from rest service as input stream which then I am changing into string for parsing.
public boolean isNullorEmpty(String string)
{
if(string !=null || !string.isEmpty() || string.length()>0)
return true;
else
return false;
}
Please help me out to check if string is empty or not.
The current problem in your code is that if the string you pass in argument is null, thenstring !=null is evaluated to false. Hence you'll try to evaluate !string.isEmpty() which will lead to a NullPointerException.
On the other hand if you pass a String that is not null (ex "" or "test"), string != null is evaluated to true and hence you return true.
So to fix that you should, as the name of your method suggests, check if the String is null OR empty.
But since you're on android, don't reinvent the wheel and use TextUtils.isEmpty(CharSequence str).
boolean isEmpty = TextUtils.isEmpty(myString);
Returns true if the string is null or 0-length.
If you want to look about how is it implemented:
427 public static boolean isEmpty(CharSequence str) {
428 if (str == null || str.length() == 0)
429 return true;
430 else
431 return false;
432 }
Well, this can be handled in plain java like:
And it can be written like:
public boolean isStringEmpty (){
if(str ==null || str.isEmpty () || str.trim().equals("")){
return true;
}
return false;
}
I need to see if a text field has an empty value. I need to see if
if(Double.parseDouble(distanceTf.getText())==0)
I know 0 won't work. I also know null won't work and I know .equals won't work.
Does anyone know how I can compare this line of code to a null value?
if (stageTf.getText().equals("") || Double.parseDouble(distanceTf.getText()) == null) {
JOptionPane.showMessageDialog(null, "You did not enter both a stage number and distance");
return;
}
Thanks for all the above replies but they don't work.
The part of the code I have trouble with is:
if (Double.parseDouble(distanceTf.getText())==null)
The rest of it is fine.
I have tried putting this outside the if statement and using distanceTf.getText().equals("")
in the if statement but this doesn't work either.
I just can't find out how to assign an empty value to the line of code for a double.
I know null, .equals or "" won't work.
You're not clear on which value could be null, so I'll assume both.
Since Double.parseDouble requires a non-null argument, you need to check it for null.
if(null != distanceTf.getText() && Double.parseDouble(distanceTf.getText()) != 0.0)
stageTf.getText() could return null too, but if you're guaranteed to be comparing a known non-null String against null, it would return false. So, this comparison is safer:
if("".equals(stageTf.getText())
The important thing to understand is: what you mean with null value? A null reference or an empty string?
You could do
stageTf.getText().isEmpty()
to check if the string is empty and parse it only if it contains something.
// here remember it's still wrong
if (!stageTf.getText().isEmpty() && Double.parseDouble(distanceTf.getText()) == null) {
Second problem: Double.parseDouble doesn't return null since it returns a native type.. it thrown an exception if something went wrong. So you can catch NumberFormatException.
Then you could write:
try {
double result;
if (!stageTf.getText().isEmpty() && (result = Double.parseDouble(distanceTf.getText()))) {
/* i think you need the result of the conversion, so i saved it in result */
}
}
catch (NumberFormatException e) { /* something went wrong! */ }
You need to test if the field is empty first. You did it correctly with your first conditional on the stageTf field. You need to do the same with the distanceTF field. This means nesting your conditional statements.
if(stageTF.getText().equals(""))
if(distanceTF.getText().equals("")){
/* ... */
} else {
//here it is safe to test for exceptions by using a try/catch
try{
//here you can parse the string to your Double
}catch(NumberFormatException nfe){ /* ... */ }
}
first of all you should check for null before empty because if the value is null you'll get a NullPointerException on the first one.
Second you'll get a NullPointerException if distanceTf.getText() is null on the Double.parseDouble
Double.parseDouble() doc
what I would do is create a method validate as follows:
private boolean validate(String field){ //where field = stageIf.getText() for example
if(field != null && field.trim().length() > 0)
return true;
else return false;
}
Parse outside if statment, then just compare :
if(distanceTf.getText() == "")
What is the difference between these two methods?
public boolean nameControl(String str)
{
if (str.trim().isEmpty()) return false;
if (str.trim().length() == 0) return false;
return true;
}
I need find out that str should have at least one character.
There is no real difference between them.
Javadocs for isEmpty()
Returns true if, and only if, length() is 0.
From the Javadoc:
isEmpty
public boolean isEmpty()
Returns true if, and only if, length() is 0.
For Java 6+
isEmpty() works since Java 6 and length == 0 works since Java 1.2+ or possibly an older version.
If you notice, the implementation of the method
Apache Commons Lang (for Java 5+)
public static boolean isEmpty(String str)
of the class org.apache.commons.lang.StringUtils from Apache Commons Lang use str.length() == 0 in order to support Java 5.0+.
Luckily for you this is already documented:
IsEmpty():
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#isEmpty()
Length():
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#length()
If you need to detect if a string has at least one (non-whitespace) character, I would try:
public boolean nameControl(String str) {
if (str == null) return false;
else if (str.trim().length() == 0) return false;
return true;
}
If a string containing only whitespace should return true I would remove the trim as follows:
public boolean nameControl(String str) {
if (str == null) return false;
else if (str.length() == 0) return false;
return true;
}
Wanted to update on this:
I Observed if the string is having newline char(\n or \r), that time
length fun gives you not zero value but isEmpty fun standout with
value as true which is expected.
Approach one.
if (graphType.equals("All") || graphType.equals("ALL"))
Aprroach two.
if ("All".equals(graphType) || "ALL".equals(graphType))
What is the difference between these two approaches?
Why the below one is better?
The second one is better, as if graphType is null, the first code snippet will throw a NullPointerException.
Note that you can simplify your code using "ALL".equalsIgnoreCase(graphType) (if you accept values such as AlL or aLL...)
Edit regarding your comment:
If graphType is null, in the first case, you will get a NullPointerException. In the second case, the evaluation of the equals method will be false, as "someString".equals(null); always returns false:
Here is the code of the String.equals(String) method:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
(source)
The interesting line is if (anObject instanceof String) {. When you call the instanceof statement on a null object, this test always returns false. That's why "anyString".equals(null); will return false.
I feel the need to present a contrarian viewpoint to the accepted answer:
The first one is better, precisely because it will throw a NullPointerException in the case where graphType is null.
Generally, if an unexpected condition is found, you want to halt and throw an Exception as early as possible, otherwise you may continue to execute the program in an invalid state and the bug may become fiendishly difficult to track down.
This is sometimes referred to as the "fail-fast" principle.
romaintaz answer is absolutely correct. However, if you're like me, you might prefer to use the first approach to make your code easier to read. This is where assertions come into play:
assert graphType != null : "graphType is null";
if (graphType.equals("All") || graphType.equals("ALL"))
The question is whether your users will find a creative way to make graphType = null once you've finished testing.
The other thing I don't like about the second approach is that it fails silently in the case that graphType is unexpectedly null -- It prevents a runtime error, but may present a bug that's difficult to track down.