Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short condition in java

Tags:

java

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)

like image 705
Sonrobby Avatar asked Feb 19 '23 01:02

Sonrobby


1 Answers

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:

  • Arrays
  • Foreach
like image 147
Aaron Avatar answered Feb 28 '23 01:02

Aaron