Compare value of 3 or more elements at once in JAVA


Is it possible to somehow compare the value of 3 or more items at the same time?

Something like this:

if (a == b == 3) {


If I stick to answering your question, since you start with Is it possible … yes, it is possible .

Is it correct ?? I already doubt it, this type of expressions gives more room for mistakes and errors than normal syntax. For example, the code that you 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)

  1. First a == b : Let's imagine that this is true, which will return true , obtaining the following expression: if (true == 3)
  2. Second step, true == 3 : What we have here is an incomparable error types: boolean and int , meec, it turns out that this if so easy to understand was not even valid!

Then this cannot 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 "It is correct" … but obviously comparing true == true does not make much sense so although it is technically possible to do what you want, it should not be , because in the best of cases not contributes absolutely nothing.

In the worst case … well, it will give an error, and although not an error, the moment you want to add a different condition to the check you will start to complicate things so that everything runs correctly.

If we all use a == b && b == 3 's for a reason, and it's much more readable !

Scroll to Top