Tenebris Mortem
Tenebris Mortem

Reputation: 93

Java increment logical problem (increment in conditional statements)

I have this assessment that is given to me, but this two questions stuck in my mind. These two codes seem similar but is giving of different output based on the increment

Code #1:

package com.company;
class Main {
public static void main(String [] args) {
                boolean x = true;
                boolean y = false;
                short z = 42;

                if((z++ == 42) && (y = true))
                    z++;
                if((x = false) || (++z == 45))
                    z++;
                System.out.println("z = " + z);
                }
}

This code seemed fine it increments the value that it should be increment and returning that value to "z" thus the output

Output:

z = 46

Process finished with exit code 0

But the second code seemed different as it does not save the incremented value

Code #2: package com.company;

public class Test2

{
    public static void main(String [] args) {
        boolean x = true;
        boolean y = false;
        short z = 42;
        if((x == true) && (y = true))
            z++;
        if((y == true) || (++z == 44))
            z++;
        System.out.println("z = " + z);
    }
}

This one does not save the increment on the second if conditional statement like the first code

Output:

z = 44

Process finished with exit code 0

Am I missing something important?

Upvotes: 0

Views: 235

Answers (1)

MC Emperor
MC Emperor

Reputation: 22977

This is because the logical OR operator (||) is short-circuiting: if the first condition is known to be true, then the second condition is not executed at all.

That means the z++ in (++z == 44) is not executed, hence the end result is 44 instead of 45.

As mentioned in the comments, the bitwise OR operator (|) is not short-circuiting, so both statements are always executed.


Code like this can be very confusing. Code should be primarily readable. Never use an assignment within a condition. b = false can be easily confused with b == false. Also avoid using increment operators in the middle of other operations, only as standalone expressions.

Upvotes: 3

Related Questions