Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The output for the code below is:
VB
1. true
2. false
1. true
2. true


I understand why the 1st line of output should be true.

I don't understand why the 2st line of output should be false, because 13 <= 5 and 13 != 12 makes 'false', 'false' and 13 > 10 makes 'true'.

I don't understand why the 3rd line of output should be true, because 12 > 10 or 12 <= 5 makes 'true', and 'true' and 12 != 12 makes false.

I understand why the 4rd line of output should be true.




C#
public class MyProgram
{
    public void start()
    {
        doBooleans(12);
        doBooleans(13);
    }

    private void doBooleans(int value)
    {
        boolean result;

        result = value > 10 || value <= 5 && value != 12;
        System.out.println("1. " + result);

        result = (value > 10 || value <= 5) && value != 12;
        System.out.println("2. " + result);
    }
}
Posted

 
Share this answer
 
Quote:
I don't understand why the 2st line of output should be false, because 13 <= 5 and 13 != 12 makes 'false', 'false' and 13 > 10 makes 'true'.

Because the second line is still output of your first method call, you pass 12 as parameter (and not 13), so you actually have (12 > 10 || 12 <= 5) && 12 != 12. The part inside parentheses is true, and the last part is false, so you have true && false which is false.
Quote:
I don't understand why the 3rd line of output should be true, because 12 > 10 or 12 <= 5 makes 'true', and 'true' and 12 != 12 makes false.

The third line is the output of the second method, so you pass 13 as parameter (and not 12), and you have 13 > 10 || 13 <= 5 && 13 != 12. So, the first part, 13 > 10 is true, and the second part is false, and true || false is true.
 
Share this answer
 
v2
First, keep this chart [^] with you and refer to it all the times.
Let do one example, this line without parenthesis
12 > 10 || 12 <= 5 && 12 != 12

The precedence order is like this: (Higher precedence on the left)
!, <= , !=, &&, ||

so that line becomes:
true || false && false

Since && takes precedence over ||, it next becomes:
true || false

What is the final outcome, true!
You should be able to figure out the other one. My advice is always use parenthesis to make your intention clear and explicit.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900