Assuming object
and whatItShould
are primitive types and can be compared using ==
, you should use ==
:
conditionIsTrue = (object == whatItShould);
Assuming object
and whatItShould
are object references, you should use equals
method:
conditionIsTrue = (object.equals(whatItShould));
Note that equals
method, if not overridden, will end using ==
for comparing the references.
From your edit:
I am not looking for an alternative to change the code with object.equals or other, this condition was an example and usually they are more complex. I would like to do what is the best way only between #1 and #2.
You should post what you're looking for exactly, so there won't be any double interpretation for a specific programming problem.
Anyway, you may initialize the variable with a default value and define the real value after several conditions (using an int
variable because boolean
is misleading):
int myVariable = 0;
if (<condition1> && <condition2> &&
(<condition3> || <condition4>) ...) {
myVariable = //real value
}
This way, you avoid compiler problems in case not all the paths initialize the variable accordingly, which may happen when using your first approach.
But still, if your conditions are in one single line, it would be better using Ternary Operator:
int myVariable = (condition1> && <condition2> &&
(<condition3> || <condition4>) ...) val1 : val2;
Also, you can nest the ternary operators in case to have multiple paths:
int myVariable = (<condition1>) ?
val1 : (<condition2> && <condition3>) ?
val2 : val3;