How to check if two expressions are equivalent or not in java

I want to check if two expressions are equivalent or not in Java. Let's say I have two expressions:
exp 1:

A && B && ( C || D)  

exp 2:

B && ( C || D ) && A  

I want to check if these two expressions are equivalent or not.

What I mean by equivalent was, if we say that we have two expressions, then these two expressions should have the same tokens (A, B, C, D) and the same relationship operators between them. And should return the same values ​​for all inputs. I do not want to consider the order in which java does these things. And I need a library or some piece of Java code for this. Information about the algorithm is also excellent.

+4
source share
1 answer

They are not associated with a short rating. In Java, A && Breturns false immediately when Aevaluated to false. It matters, for example. when it comes to Exceptionsor logical methods that are not pure functions.

You can try the following experiment:

public class Test {

    public n = 0;
    public boolean A() {
        System.out.println("A");
        return false;
    }
    public boolean B() {
        System.out.println("B");
        return true;
    }
    public boolean C() {
        n++;
        return true;
    }
    public boolean D() {
        n = n*2;
        return false;
    }
    public static void main(String[] args) {
        Test test = new Test();
        if (test.A() && test.B()) { System.out.println("true"); }
        if (test.B() && test.A()) { System.out.println("true"); }
        if (test.C() && test.D()){}
        else {System.out.println(t.n);}
        t.n = 0;
        if (test.D() && test.C()){}
        else {System.out.println(t.n);}
        t.n = 0;
        boolean c = test.C();
        boolean d = test.D();
        if (d && c){}
        else {System.out.println(t.n);}
    }
}

It shows the consequences of a short assessment associated with a side effect.

+4
source

Source: https://habr.com/ru/post/1664135/


All Articles