Check two arguments in Java, either both not null or both null elegantly

Solution 1:

There is a way using the ^ (XOR) operator:

if (from == null ^ password == null) {
    // Use RuntimeException if you need to
    throw new IllegalArgumentException("message");
}

The if condition will be true if only one variable is null.

But I think usually it's better to use two if conditions with different exception messages. You can't define what went wrong using a single condition.

if ((from == null) && (password != null)) {
    throw new IllegalArgumentException("If from is null, password must be null");
}
if ((from != null) && (password == null)) {
    throw new IllegalArgumentException("If from is not null, password must not be null");
}

It is more readable and is much easier to understand, and it only takes a little extra typing.

Solution 2:

Well, it sounds like you're trying to check whether the "nullity" condition of the two is the same or not. You could use:

if ((from == null) != (password == null))
{
    ...
}

Or make it more explicit with helper variables:

boolean gotFrom = from != null;
boolean gotPassword = password != null;
if (gotFrom != gotPassword)
{
    ...
}