Interesting question: Can (a==1 && a==2 && a==3) ever evaluate to true? In Java / in JavaScript?

JavaScript

In JavaScript we can achieve our goal by this way:


const a= {
    i : 1,
    toString : function () {
              return a.i++;
      }
}

if( a==1 && a==2 && a==3) {
      console.log(‘Hello World!’);
}

If you remember you == operator works you can create an object with custom toString or valueOf function that changes what if returns each time it was invoked.

Second thing helps you is casting types of input operands : if one operand is a number it will attempt to convert second operand to a number by first calling valueOf if it callable, and if it failed will call toString and try to cast result to a number. If you see using toString gives the same result but longer path then valueOf.

Java

In Java we can achieve the same result using multiple threads.


public class Test{      
       private volatile int a;

       public void start(){
               new Thread(this::test).start();
               new Thread(this::change).start();
        }

        public void test(){
            while(true) {
                  if (a==1 && a==2 && a==3) System.out.println(“Success”);
               }
        }

        public void change(){
               while(true){
                      for(int i =1; i<4; i++) a=i;
                }
         }

        public static void main(String[] args){
               new Test.start();
        }
}

Without volatile key word the compiler is allowed to cache a variable or replace the if statement with if(false). With volatile key word you will get Success always.