Sonrobby
Sonrobby

Reputation: 3162

Short condition in 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)

Upvotes: 4

Views: 208

Answers (5)

Name
Name

Reputation: 2045

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:

Upvotes: 4

Shivam
Shivam

Reputation: 2132

if is redundant here, just use return !(a == null || b == null || c == null || d == null);

Upvotes: 0

Makoto
Makoto

Reputation: 106470

It seems that this could be expressed a bit more elegantly with a foreach loop and a String vararg. It would read nicer and allow you to easily debug your statement.

// method only returns true if all strings are non-null
public boolean all(String... strings) {
    for(String str : strings) {
        if(null == str) {
           return false;
        }
     }
     return true;
 }

You would then call it in this manner:

return all(a, b, c, d); // will return false if any of these are null, otherwise true.

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

- You are using Non-Short circuit OR to evaluate the condition, which i think is the most apt and simplest in this case.

- So your solution is what it needs to be.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198341

Nope, your solution is the simplest possible.

Upvotes: 3

Related Questions