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.
Related
Could there be a string that
str.equals(str) is False?
Or in another way:
if(!str.equals(str)){
System.out.println("-1");
}
Is there any way that the println line of code gets covered by a test?
No, there couldn't. Here's the source code in java 17. As you can see, when the two objects are the same, the equals method always return true.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
return (anObject instanceof String aString)
&& (!COMPACT_STRINGS || this.coder == aString.coder)
&& StringLatin1.equals(value, aString.value);
}
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
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 am newbie in java.
Here is my code:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
else return false;
}
but compiler gives:
Error: public boolean endsLy(String str) {
This method must return a result of type boolean
Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider adding a last line in the method return some_value;
so a value is always returned.
You are not handling the branch where (str.length()>=2, but !str.substring(str.length()-2).equals("ly"). Remove the else from the final return statement:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
return false;
}
An even simpler alternative (also less prone to the kind of error you are having), is to have only a single return statement:
public boolean endsLy(String str) {
return str.length()>=2 && str.substring(str.length()-2).equals("ly");
}
Or simply :
public static boolean endsLy(String str) {
return str.length()>= 2 && str.substring(str.length()-2).equals("ly");
}
You might also check if the String is not null.
return str != null && str.length()>= 2 && str.substring(str.length()-2).equals("ly");
here a correction:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
else
return false;
}
else{
return false;
}
}
This error means that there might be a possibility that the function will not return anything under some circumstances.
so if this condition => if(str.length()>=2) stands true the code will enter into it. Now if this condition is false => if(str.substring(str.length()-2) the function will have nothing to return. So this is a wise thing that the error prompted.
This means that not all conditions in this function return a bool value. There is a chance that conditions may occur when function does not have anything to return.
because you do not have a boolean value is returned in case !str.substring (str.length () -2). equals ("ly")
if you want to check that your chain is composed of four characters in the last two are "ly" you can use the following codes:
public boolean endsLy(String str) {
if (str.length() == 4 && str.endsWith("ly"))
return true;
return false;
}
Avoid multiple false return statement as return value is true only for condition if(str.substring(str.length()-2).equals("ly")). Following code is for reference.
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
}
return false;
}
I have some simple logic to check if the field is valid:
private boolean isValidIfRequired(Object value) {
return
(required && !isEmpty(value)) || !required;
}
it tells that the field is valid if it's either required and not empty or not required.
I don't like this required || !required part. Something with just required would be better.
How do I simplify this method to make it more readable and simple?
How 'bout:
private boolean isValidIfRequired(Object value) {
return !required || !isEmpty(value);
}
or (thanks, #Peter Lawrey)
private boolean isValidIfRequired(Object value) {
return !(required && isEmpty(value));
}
In either case, if required is false, the || or && expression will short-circuit and isEmpty will never be called. If required is true, the second half of the || or && will be evaluated, calling isEmpty and returning the (inverted) result of that call.
The expected return of isValidIfRequired() is to return true.
So the exceptional cases must be put at the beginning as guardian clausules:
private boolean isValidIfRequired(Object value) {
if (required && empty(value)) //guardian clausule
return false;
return true;
}
for me the above code is more human-readable than using together expresions containing ANDs ORs and negations