7

I was wondering whether its possible in java to evaluate multiple variables together in if-else condition like in python.

actual code

if(abc!=null && xyz!=null)
{//...}

dummy code

if(abc && xyz !=null)
{// will it be possible}
Community
  • 1
  • 1
Aman Gupta
  • 5,548
  • 10
  • 52
  • 88

5 Answers5

20

FIRST DRAFT

You can write smth like this:

boolean notNull(Object item) { 
    return item != null;
}

then you could use it like:

if (notNull(abc) && notNull(xyz)) {
    //...
}

UPDATE 1:

I came up with a new idea, write function using varargs like:

boolean notNull(Object... args) {
    for (Object arg : args) {
        if (arg == null) {
            return false;
        }
    }
    return true;
}

usage: (you can pass to function multiple arguments)

if (notNull(abc, xyz)) {
    //...
}

UPDATE 2:

The best approach is to use library apache commons ObjectUtils, it contains several ready to use methods like:

jtomaszk
  • 9,223
  • 2
  • 28
  • 40
7

the only way this would work is if abc was a boolean (and it wouldn't do what you're hoping it would do, it would simply test if abc == true). There is no way to compare one thing to multiple things in Java.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
1

It's Impossible in java, you can use Varargs:

public boolean  checkAnything(Object args...){
  for(Object obj args){
    if(...)
  }
  return ....;
}

See also:

Community
  • 1
  • 1
Rong Nguyen
  • 4,143
  • 5
  • 27
  • 53
1

Its not possible to that in Java. Instead you can do something like this:-

public boolean checkForNulls(Object... args){
    List<Object> test = new ArrayList<Object>(Arrays.asList(args));
    return test.contains(null); // Check if even 1 of the objects was null.
}

If any of the items is null, then the method will return true, else it'll return false. You can use it as per your requirements.

Rahul
  • 44,383
  • 11
  • 84
  • 103
0

IMHO First is the better way and possible way.

Coming to second way ..if they are boolean values

if(abc  && xyz )
{//...}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307