Question:
Is it possible to somehow compare the value of 3 or more items at once?
Something like this:
if (a == b == 3) {
//código
}
Answer:
If I stick to answering your question, since you start with Is it possible… yes, it is possible .
is it correct ?? I doubt it, this type of expression is more likely to make mistakes and errors than normal syntax. For example, the code that you have put in the question would not work since in java the operations are evaluated from left to right , not at the same time … what does this mean in your code? Step by step:
if (a == b == 3)
- First
a == b
: Let's say this is true, which will returntrue
, getting the following expression:if (true == 3)
- Second step,
true == 3
: Here what we have is an incomparable error types: boolean and int , meec, it turns out that that easy-to-understandif
was not even valid!
So this can't be done 🙁
Yes, it can be done:
int a = 4, b = 4;
if(a == b == true)
System.out.println("Es correcto");
This is a valid expression that will print the message "That's right"… but obviously comparing true == true
doesn't make much sense so even though it's technically possible to do what you want, it shouldn't , at best it won't. contributes absolutely nothing.
In the worst case… well, it will give an error, and even if it doesn't give an error, the moment you want to add a different condition to the check, you will begin to complicate yourself excessively so that everything runs correctly.
If we all use a == b && b == 3
it is for a reason, and it is much more readable !