I have 4 String
variables: a, b, c , d.
I check if one of them is null
then return false
.
so i do:
if(a==null || b ==null || c ==null || d ==null) return false;
Has any short way for this?
(i'm beginning for java)
If your method looks like this:
public boolean foo() {
String a = "a", b = "b", c = "c", d = "d";
if(a == null || b == null || c == null || d == null) {
return false;
}
return true;
}
Then there is a way you could reduce code. You could do this instead:
public boolean foo() {
String a = "a", b = "b", c = "c", d = "d";
return (a != null || b != null || c != null || d != null);
}
But, if you had more strings to test, say, 10, or even 100, a strategy that would require less code would be to put the strings into an array and use a for-each loop. In fact, the following method would work with any type of object, not just strings.
public boolean containsNullObject(Object... objs) {
// loop through each string
for(Object o : objs) {
if(s == null) { return false; } // return false if string is null
}
// if there was no instance of a null object, return true
return true;
}
If you don't know what an array or for-each loop is, look at these:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With