1
public class TestPass {

int a,b;
TestPass(int i,int j)
{
    a=i;
    b=j;
}
boolean equals(TestPass o)
{
    if(o.a==a&&o.b==b)
        return true;
    else
        return false;
}

}

  class Test
  {
  public static void main(String[] args)  
  {
  TestPass ob1=new TestPass(100, 22);
  TestPass ob2=new TestPass(100, 23);


    System.out.println("Condition="+ob1.equals(ob2));
}

}

Output:

Condition=false

I cannot find the logic with this output,bcoz 'if(o.a==a&&o.b==b)' code is used AND short circuit operator(&&),it only checks left hand side of operator(i think so).

        TestPass ob1=new TestPass(100, 22);
        TestPass ob2=new TestPass(100, 23);

Here i gave different values,but i think AND short circuit operator(&&) only checks left hand side,my expected output is True!,I think i'm wrong.I need clarification, Expect your help.

Enrique_Iglesias
  • 121
  • 1
  • 2
  • 11

3 Answers3

0

The short-circuit only applies if the left side is false. If the left side is true, it will go on to check the right-hand side.

In your case o.a==a is true, so it checks the right-hand side: o.b==b is false, making it false overall.

stripybadger
  • 4,539
  • 3
  • 19
  • 26
0

This is the rule about the short-circuit you need to keep in mind.

╔══════════╦════════════════════════════════════════════════════════════════════════╗
║ Operator ║                           short-circuit                                ║
╠══════════╬════════════════════════════════════════════════════════════════════════╣
║ A && B   ║ if A==false then the B expression is never evaluated                   ║
║ A || B   ║ if A==true then the B expression is never evaluated                    ║
╚══════════╩════════════════════════════════════════════════════════════════════════╝
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

One way of thinking about it is to split the if-condition

boolean equals2(TestPass o) {
    if (o.a == a) {
        if (o.b == b) {
            return true;
        }
        return false;
    }
    return false;
}

or even

boolean equals3(TestPass o) {
    if (o.a == a) {
        return o.b == b;
    }
    return false;
}

FYI, your equals could be simplfied to return o.a==a&&o.b==b

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75