Decrement operator precedence confusion

Here is the snippet from a book:
int y = 5;
int result = y-- * 3 / --y;
System.out.println("y = " + y);
System.out.println("result = " + result);Assuming increment and decrement have highest precedence, I don't get the explanation:
Order of operations dictates that the multiplication is evaluated first(WHY???). The valueof y is 5, so 5 * 3 is 15. The multiplication is done, so the post - decrement occurs and y
becomes 4. Now the division is evaluated and y is pre - decremented to 3 before the division,
resulting in 15 / 3 , which is 5. The output of this code is:
y = 3
result = 5
Any comments would be appreciated.

AntShay wrote:
Oh, no!
There's something more I don't get :)
Why is 5 *** 3 takes place instead of 4 *** 3? Pre-decrement has higher precedence, hasn't it?
So, from my point of view this should work as follow (please correct me where I'm wrong):
int y = 5;
int result = y-- *** 3 / --y;
1) y-- gets evaluated (y=4 now)
2) --y gets evaluated (y=3)
3) 3 *** 3 = 9
4) 9/3 = 3I don't know if pre-dec has higher precedence than mult, but even if it does, that doesn't matter. That's not what precedence means. It doesn't mean you jump around and do those operations first. I just means "This is where the implied parentheses go." The only affect it has on order of evaluation is when you have to evaluate something inside the implied parens first to get an operand for the next operation.
3 + 4 * 5In the above, mult has higher precedence than add, so it's equivalent to
3 + (4 * 5)It doesn't mean "first do all multiplications, then all adds." It means the implied parens are as above.
So:
1. evaluate 3
2. evaluate the RH operand of +++
2.1 evaluate 4
2.2 valuate 5
2.3 multiply 4 *** 5 --> 20
3. evaluate 3 +++ 20
So we did the mult before the add because we had to in order to get the value of the RHS operand of the plus. Indirectly it's because mult has higher precedence, but that's just a consequence of the implied parens, and we still evaluated the 3 before doing the mult. We did NOT do "all mults first, then all adds."
Similarly, if it had been
2 + 3 + 4 * 5we would eval 2, then eval 3, then add, then eval the RHS of the second plus operator, which means we'd have to eval 4 *** 5. Note that we do NOT eval 4 *** 5 as the very first step before all adds.
Now, say pre-dec has higher precedence than mult. It may, it may not, I don't know and I don't care. It doesn't matter here, but let's say it does.
y-- * 3 / --yis the same as
(y--) * 3 / (--y)Operands are still evaluated L to R. We don't just jump around.
1. Evaluate y--
1.1 value of expression is 5
1.2 decrement y to 4
2. Evaluate 3.
3. Multiply #1 *** #2 --> 5 *** 3 = 15
4. Evaluate --y
4.1 decrement y
4.2 valueof expression is 3
5. evaluate #3 / #4 --> 15 / 3 = 5
Edited by: jverd on Feb 12, 2010 11:54 AM
Edited by: jverd on Feb 12, 2010 11:56 AM

Similar Messages

  • JAVA operator precedence table is wrong.

    I can not understand why JAVA auto-increment/decrement operator does not follow the rules of Operator Precedence table at http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
    The precedent order is as follow:
    postfix: expr++ expr--
    unary: ++expr --expr +expr -expr ~ !
    multiplicative: * / %
    From the above we know that x++/x-- is higher then ++x/--x and multiplicative is the lower then both.
    I tested the following in JAVA:
    int y,x = 2;
    y = --x * x++;
    System.out.println(x); //Output is 1.
    Why?
    Theoretically, x++ must be performed before --x, finally then the multiplication (*) and the answer should be
    x++ value=2, stored variable=3
    --x value=2, stored variable=2
    Therefore 2 * 2 = 4.
    Why JAVA is not following the rules that it setup for itself??
    After much research, my conclusion is JAVA Operator Precedence table in java.sun.com website is wrong. The right version should be the same as this website: http://www.sorcon.com/java2/precedence.htm.
    Please run your example code in JAVA before you want to prove me wrong.
    Thank you.

    Hi jsalonen, thank you for your reply. Yes, I see your theory but sorry to say that I don't agree with you. Let's take your example -x++ for our discussion below:
    First let's agree with this:
    x = 2;
    y = -x;
    System.out.println("y = " + y); // y = -2
    System.out.println("x = " + x); // x = 2
    From the above, we can see that by using the negation operator doesn't mean that we have changed the value of x variable. The system just assigns the value of x to the expression but still keeping the value of variable x. That's why we got the output above, agree?
    Now, let's evaluate your example:
    int y, x = 2;
    y = -x++;
    System.out.println("y = " + y); // -2
    System.out.println("x = " + x); // 3
    Hence below is the sequence of process:
    1. -x is evaluated first. Value in variable x is assigned to the expression. At this point the value of x is 2 and this value get negated. However the variable x still storing 2.
    2. Now x++ get evaluated, since this is a postfix increment operator, the value will get assigned first then increase. However x is already assigned, we can not assign it twice, just like if you perform x++ first, you have assigned x then increase and you didn't assign it again for the negation operator. If you did, x would be 3 and get negated to -3. Note that system also cannot perform 2++ because 2 is not a variable. Therefore it is logical to say that x is assigned to the expression and got negated by negation operator then increase the varaible x by 1. So here we increase the value of x by 1 and the result is 3. Therefore variable x is storing 3.
    Now, try the follwing
    x = 2;
    y = -x + x++;
    What is the value of x after -x? It's 2. Remember 2 is assign back to expression but x still retained the original value. If not we would expect x++ to be (-2)++, right?
    But see the output for yourself:
    System.out.println("y = " + y); // 0
    System.out.println("x = " + x); // 3
    As for the subexpression theory, sorry to say that I don't agree with you as well. See the expression below:
    y = -x + x++;
    We can identify that there are 4 operators in this statement, right? (assignment operator, negation operator, addition operator and increment operator)
    since JAVA has defined all the operators in the table and already given each of them a priory and associativity, I don't see any subexpression here. If yes why didn't they mention about subexpression rule in the table? Shouldn't that be defined explicitly so that it doesn't confuse people?
    In conclusion, I still think that JAVA need to correct the operators precedence table at http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html so that they don't confused people for another 10 years. :) Moreover the table is not complete because it did not include . and [ ] and (params) operators.

  • (Error in documentation?) Math operator precedence problem

    Hello,
    I apologize in advance, while I do know programming (I'm a PHP and Perl programmer) I'm fairly new to Java so this may well be a silly question, but that's why I am here. I hope you'll show me where my error is so I can finally set this to rest before it drives me mad :)
    (Also, I hope I'm posting this in the right forum?)
    So, I am taking a Java class, and the question in the homework related to operand precendence. When dealing with multiplication, division and addition, things were fine, the documentation is clear and it also makes sense math-wise (multiplication comes before addition, etc etc).
    However, we got this exercise to solve:
    If u=2, v=3, w=5, x=7 and y=11, find the value assuming int variables:
    u++ / v+u++ *w
    Now, according to the operator precedence table (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) the unary operator u++ comes first, before multiplication, division and addition.
    This would mean I could rewrite the exercise as:
    ((u+1)/v) + ((u+1)*w) = (3/3) + (4*5) = 1+20 = 21
    However, if I run this in Java, the result I get is 15.
    I tried breaking up the result for the two values in the Java code, so I could see where the problem is with my calculation.
    For
    System.out.println(u++ /v);
    I get 0
    For
    System.out.println("u++ *w");
    I get 15
    My professor suggested I attempt to change the values from int to float, so I can see if the division came out to be something illogical. I did so, and now I get:
    For
    System.out.println(u++ /v);
    I get 0.66667
    For
    System.out.println("u++ *w");
    I get 15.0000
    Which means that for the first operation (the division) the division happens on 2/3 (which is 0.6667) and only afterwards the u value is increased. That is, the u++ operation is done after the division, not before. The same happens with the multiplication; when that is carried out, the value of u is now 3 (after it was raised by one in the previous operation) and the first to be carried out is the multiplication (3*5=15) and only then the u++.
    That is entirely against the documentation.
    This is the script I wrote to test the issue:
    public class MathTest {
         public static void main (String [] args) {
              float u=2, v=3, w=5, x=7, y=11;
              System.out.println("Initial value for 'u': " + u);
              float tmp1 = u++ /v;
              System.out.println("u++ /v = " + tmp1);
              System.out.println("First ++ value for 'u': " + u);
              float tmp2 = u++ *w;
              System.out.println("u++ *w= " + tmp2);
              System.out.println("Second ++ value for 'u': " + u);
              System.out.println(tmp1+tmp2);
    The output:
    Initial value for 'u': 2.0
    u++ /v = 1.0
    First ++ value for 'u': 3.0
    u++ *w= 20.0
    Second ++ value for 'u': 4.0
    21.0
    Clearly, the ++ operation is done after the division and after the multiplication.
    Am I missing something here? Is the documentation wrong, or have I missed something obvious? This is driving me crazy!
    Thanks in advance,
    Mori

    >
    The fact that u++ is evaluated but in the calculation itself the "previously stored" value of u is used is completely confusing.
    >
    Yes it can be confusing - and no one is claiming otherwise. Here are some more thread links from other users about the same issue.
    Re: Code Behavior is different in C and Java.
    Re: diffcult to understand expression computaion having operator such as i++
    Operator Precedence for Increment Operator
    >
    So, when they explain that ++ has a higher precedence, the natural thing to consider is that you "do that first" and then do the rest.
    >
    And, as you have discovered, that would be wrong and, to a large degree, is the nut of the issue.
    What you just said illustrates the difference between 'precedence' and 'evaluation order'. Precedence determines which operators are evaluated first. Evaluation order determines the order that the 'operands' of those operators are evaluated. Those are two different, but related, things.
    See Chapter 15 Expressions
    >
    This chapter specifies the meanings of expressions and the rules for their evaluation.
    >
    Sections in the chapter specify the requirements - note the word 'guarantees' in the quoted text - see 15.7.1
    Also read carefully section 15.7.2
    >
    15.7. Evaluation Order
    The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
    15.7.1. Evaluate Left-Hand Operand First
    The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
    If the operator is a compound-assignment operator (§15.26.2), then evaluation of
    the left-hand operand includes both remembering the variable that the left-hand
    operand denotes and fetching and saving that variable's value for use in the implied
    binary operation.
    15.7.2. Evaluate Operands before Operation
    The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? appears to be fully evaluated before any part of the operation itself is performed.
    15.7.3. Evaluation Respects Parentheses and Precedence
    The Java programming language respects the order of evaluation indicated explicitly by parentheses and implicitly by operator precedence.
    >
    So when there are multiple operators in an expression 'precedence' determines which is evaluated first. And, the chart in your link shows 'postfix' is at the top of the list.
    But, as the quote from the java language spec shows, the result of 'postfix' is the ORIGINAL value before incrementation. If it makes it easier for then consider that this 'original' value is saved on the stack or a temp variable for use in the calculation for that operand.
    Then the evalution order determines how the calculation proceeds.
    It may help to look at a different, simpler, but still confusing example. What should the value of 'test' be in this example?
    i = 0;
    test = i++; The value of 'test' will be zero. The value of i++ is the 'original' value before incrementing and that 'original' value is assigned to 'test'.
    At the risk of further confusion here are the actual JVM instructions executed for your example. I just used
    javap -c -l Test1to disassemble this. I manually added the actual source code so you can try to follow this
            int u = 2;
       4:iconst_2       
       5:istore  5
            int v = 3;
       7:iconst_3       
       8:istore          6
            int w = 5;
      10:iconst_5       
      11:istore          7
            int z;
            z = z = u++ / v + u++ * w;
       13:  iload   5
       15:  iinc    5, 1
       18:  iload   6
       20:  idiv
       21:  iload   5
       23:  iinc    5, 1
       26:  iload   7
       28:  imul
       29:  iadd
       30:  dup
       31:  istore  8
       33:  istore  8The Java Virtual Machine Specification has all of the JVM instructions and what they do.
    http://docs.oracle.com/javase/specs/jvms/se7/jvms7.pdf
    Your assignment to z and formula starts with line 13: above
    13: iload 5 - 'Load int from local variable' page 466
    15: iinc 5, 1 - 'Increment local variable by constant' page 465
    18: iload 6 - another load
    20: idiv - do the division page
    21: iload 5 - load variable 5 again
    23: iinc 5, 1 - inc variable 5 again
    26: iload 7 - load variable 7
    28: imul - do the multiply
    29: iadd - do the addition
    30: dup - duplicate the top stack value and put it on the stack
    31: istore 8 - store the duplicated top stack value
    33: istore 8 - store the original top stack value
    Note the description of 'iload'
    >
    The value of the local variable at index
    is pushed onto the operand stack.
    >
    IMPORTANT - now note the description of 'iinc'
    >
    The value const is first sign-extended to an int, and then
    the local variable at index is incremented by that amount.
    >
    The 'iload' loads the ORIGINAL value of the variable and saves it on the stack.
    Then the 'iinc' increments the VARIABLE value - it DOES NOT increment the ORIGINAL value which is now on the stack.
    Now note the description of 'idiv'
    >
    The values are popped
    from the operand stack. The int result is the value of the Java
    programming language expression value1 / value2. The result is
    pushed onto the operand stack.
    >
    The two values on the stack include the ORIGINAL value of the variable - not the incremented value.
    The above three instructions explain the result you are seeing. For postfix the value is loaded onto the stack and then the variable itself (not the loaded original value) is incremented.
    Then you can see what this line does
      21:  iload   5 - load variable 5 againIt loads the variable again. This IS the incremented value. It was incremented by the 'iinc' on line 15 that I discussed above.
    Sorry to get so detailed but this question seems to come up a lot and maybe now you have enough information and doc links to explore this to any level of detail that you want.

  • Why we use increment or decrement operator

    Hi. I want to know that is there any advantage of using the increment or the decrement operator. Does it makes the code a bit faster to run, etc.
    Actually i find these operators to be a bit confusing. so want to ask why should we use them and when.
    Thanks.

    baftos wrote:
    I am not kidding. It's a personal opinion that may be wrong.
    I'll tell you why I think what I think and I would be glad to change my opinion if someone shows me the light.
    Those operators are just syntactic sugar.So is a bunch of other stuff in Java (imports and the foreach loop, for example). Syntactic sugar is a good thing when it makes common idioms more compact, or stand out as what they are, as opposed to just another instance of a more general case. (Although I don't really consider these syntactic sugar.)
    Everything they do can be done otherwise more clearly.I disagree. "Increment" is an all-pervasive operation in programming. Sure, it can be done as just another case of x = x + something, where in this case something happens to be one, but in my opinion, that's not as descriptive. x++ is compact, concise, easy to read, and stands out clearly as "increment x".
    Without them the language would be just simpler.
    No more riddles about i=i++, Any language feature can be abused or misunderstood. That in itself is not a valid argument against including it. This misunderstanding is very easy to correct. It's on the same scale with redeclaring a member as a local and then wondering why you're getting NPE when trying to use the member elsewhere. It's not even in the same league as things like operator overloading or MI of implementation.
    why n=i+1 requires cast, but not n=++i, the relation between boxing and the ternary etc.Again, these are little quirks, corner cases that cause some minor confusion but not major problems. To me this kind of stuff is no different than stuff like using compile-time constants for case conditions or to assign a wider integer type to a narrow one without a cast. It's stuff that makes the language easier to read and write for a lot of common use cases, at the cost of some minor complexity in the corners.
    They were retained from C, while other things were discardedWhich is neither an argument for nor against them.
    Edited by: jverd on Oct 31, 2009 9:37 AM

  • Help with operator precedence.

    I'm having trouble telling whether + and - signs are unary or binary in figuring out operator precedence. I understand that the unary makes things positive and negative and that the binary is addition and subtraction. here is an example from my notes.
    a + b > - c I I ! d && e == f - g % h. It says that the a+b is the first order of evaluation. Heres the full order is gives for the order of evaluation. (132948765) What I don't understand is how the first plus is unary and not binary because it seems to be addition, and I was under the influence that the unary+ is not used very much. Could someone clear this up. Thanks
    Edited by: javaguy84 on Oct 4, 2007 10:38 PM
    Edited by: javaguy84 on Oct 4, 2007 10:39 PM

    What I don't understand is how the first plus is unary and not binary because it seems
    to be additionYou're right the first plus is a binary operator - otherwise the "a" would be left stranded: unconnected to the rest of the expression.
    In trying to figure out why the plus is the first operator (first in order of operation I mean, not leftmost) it might be helpful to bear in mind: With binary operations (and other places) Java evaluates things left to right. The left hand operand will be completely evaluated before work starts on the right hand operand.
    This is in addition to operator precedence and parentheses.
    See if that helps figure out the order.
    jverd is correct this is a dumb question. It has as much to do with expressions and their evaluation as a crossword puzzle has to English literature. Its dumbness is not of your making, but you might like to raise with your teacher that view that expressions like this would be wrong even if they were correct.
    (Finally there isn't really an order completely defined for this expression because some of the subexpressions may - or may not - ever be evaluated.)
    Post back if you can't figure it out. But give your reasons. Ie list step by step how you think the expression would be evaluated.
    [Edit] Except that assignment operators are evaluated right to left!

  • Operator precedence and associatively

    Greetings,
    I'm a Java newbie, and reflecting that is this concept questions. I'm trying to understand operator precedence and associatively. I understand that operator associatively is how items are read in an expression - like, they (items) are read from left to right. The book I'm trying to learn from talks a lot about this but it all blows over my head.
    I was wondering if one of you Java wizards could explain this concept to me in greater detail. I would really appreciate any thoughts.
    thanks a lot!
    Stephen

    Thousands will disagree with me, but IMHO you should use brackets to make things clear rather
    than assume everyone knows all the precedence rules.
    Basically the concept is:
    1 + 2 * 3 : Does the plus get done first (leaving 3 * 3) or does the the multiply (leaving 1 + 6) ?
    * has a higher precedence so you get 1 + (2 * 3). If you had written it that way in the first place
    you would be less likely to get it wrong when debugging at 3am.
    Associativity comes in when you have two operators of the same precedence.
    Hope this helps !

  • Operator Precedence Doubt

    public class PrecedenceEx {
         public static int m(int i) {
              System.out.print(i + ", "); return i;
         public static void main(String s[]) {
                  m(m(1) - m(2) + m(3) * m(4));
    Output is : 1, 2, 3, 4, 11
    I used operator precedence and got 3, 4, 1, 2, 11
    Why is operator precedence not applicable here.

    Operator precedence is applicable.
    m(1) + m(2) * m(3)
    In the above, precendence does NOT mean that m(2)*m(3) is executed before m(1). Expressions are evaluated left to right. Precedence simply means that the * binds more tightly than the +, so that it's like
    m(1) + ((m(2) * m(3))
    rather than
    (m(1) + m(2)) * m(3).
    So m(1) is evaluated first, then m(2), then m(3), then the results of m(2) * m(3) are computed, and the result of that is added to the m(1) that was computed previously.

  • Operator precedence && or ||.. which is greater

    http://www.csc.calpoly.edu/~csturner/courses/101/Hints/operator_precedence.html
    http://www.uni-bonn.de/~manfear/javaoperators.php
    The above two links are where i read about operator precedence. They say && has more precedence than ||, if thats the case then the output for the following should be true, true , true, but the actual output is as below. Can anyone give me a chart that lists the operator precedence correctly. or have i missed something..pls let me know.. thaks..
    class ABC{
      static boolean a, b, c;
      public static void main (String[] args) {
        boolean x = (a = true) || (b = true) && (c = true);
        System.out.print(a + "," + b + "," + c);
    output: true false false

    If && has higher precedence then shouldnt (b = true)
    && (c = true) get executed first before evaluating
    for || operator.??No.
    a || b && c
    The precedence only means that && binds tighter than || -- that is, that, as somebody said earlier, the above is equivalent to
    a || (b && c)
    rather than
    (a || b) && c
    It's still evaluated left to right though. First a, then, iff a is false, (b && c). But for us, since a was true, there was no need to eval (b && c)

  • Operator precedence: prefix vs postfix incremental

    Hello pal,
    I am confused whether postfix incremental operator has more precedence that the prefix incremental operator or not.
    The following URL shows that postfix incremental operator has superior precedence.
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html
    I wrote a simple program to test the concept,however, it looks like they have equal precedence.
    public class Precedence {
            public static void main(String[] args) {
                    int i, k;
                    k = 10;
                    i = ++k * k++;
                    System.out.println("k = 10;");
                    System.out.println("i = ++k * k++;" + " = " + i);
                    k = 10;
                    i = k++ * ++k;
                    System.out.println("k = 10;");
                    System.out.println("i = k++ * ++k;" + " = " + i);
    }The output surprises me, though. (Note that I run the program on IBM JRE 1.3.1 build cn131w-20020403 ORB130.)
    k = 10;
    i = ++k * k++; = 121
    k = 10;
    i = k++ * ++k; = 120
    Question: Is this a correct behaviour ... or my test program is wrong?

    Yes, this is correct behavior.
    k = 10;
    i = ++k * k++;
    ++k is incremented to 11, but k++ is not because its a postfix increment, it is assigned after i. So this ends up being 11 * 11 which gets you 121.
    k = 10;
    i = k++ * ++k;
    k++ is assign after the operator, so it remains 10. ++k is a prefix increment, so this becomes 11, but the postfix increment makes it 12. So this ends up being 10 * 12, which becomes 120.
    It all makes sense if you look at this code. It's actually what's happening:
    public class Precedence {
            public static void main(String[] args) {
                    int i, k, j;
                    j = 0;
                    k = 10;
                    i = ++k;
                    i = i * k++;
                    System.out.println("k = 10;");
                    System.out.println("i = ++k * k++;" + " = " + i);
                    k = 10;
                    i = k++;
                    i = i * ++k;
                    System.out.println("k = 10;");
                    System.out.println("i = k++ * ++k;" + " = " + i);

  • Different operating systems confusing router

    Hardwired computer hooked to WRT54G V8  with Windows XP works fine. Add Acer laptop either hardwired or wireless with Vista basic and it will not stay connected to internet or not connect at all. If XP computer unplugged from router, Acer will work perfectly. XP plugged back in, Acer will kick offline and not reconnect. Acer tech support via Verizon tech. support says incompatability issues. The two operating systems are confusing the router. What is the fix?
    Thanks 

    Might be possible there is either "Network Bridge" or "Broadband connection"
    present under network connection of XP laptop .....
    Open control panel >> network connection >> check if there are such connections installed .... delete it .....
    Only Local Area Connection should show connected status ....
    Check the IP address under Local Area Connection ..... open the setup page of router & see the Internet Ip address on status tab .....

  • JLS - operator precedence

    Hi,
    Just wondering - is there a sort of table with operator's precedence in JLS ?
    I couldn't find it there ... There are some on the net but I wanted to
    get to the very source ;) All I could find is this:
    http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#4779
    , but it doesn't seem to exactly specify the precedence (does it ? I must admit that
    I got through it briefly ...)
    Cheers,
    Adrian

    {color:#000080}Adrian
    Try this{color}
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
    {color:#000080}Darryl{color}

  • Explain - Operator precedence ??

    hi,
    Can anyone explain me the output of this program?
    class test
    static boolean a;
    static boolean b;
    static boolean c;
    public static void main(String [] args)
    boolean x = (a=true) || (b=true) && (c=true); // ??
    System.out.println(a + "," + b + "," + c);
    The output is true,false,false
    I know that operator && has a higher precedence over || operator. I don't know how the expression is getting resolved.
    Please help.

    I know that operator && has a higher precedence over
    || operator. I don't know how the expression is
    getting resolved.
    Please help.Precedence is generally left from right. Certain things violate this but it doesn't really come up much if you don't write impossible to read code.
    It looks like what happens here is that (a=true) happens first and then the expression (true) || something is evaluated. There are two OR operators in Java. | and ||. I can remember the names for the differences but this is what they are. | evaluates bothe sides regardless of whether the left side is true or not. || evaluates the left side and if it is true, returns.
    If you change the || to | you will get all true.

  • Operator precedence query ( && ,||)

    Hi,
    Please take a look at the following simple program.
    public class C {
    static boolean a,b,c;
    public static void main(String[] args){
         boolean x= (a=true) || (b=true) && (c=true);
         System.out.print(a+","+b+","+ c);
    The output of this program is true,false,false. Now this has got me all confused.
    The result I expected was true,true,true. This is the order of operation that I expected
    1) All operations within brackets are executed first .So this should set a=true,b=true and c=true.
    2) Next the && operation is executed .
    3)Lastly the || is executed
    Could someone please give explain why (a=true) is executed and the remaining parts are not executed?
    Appreciate your help. Thanks!

    To amplify on why:
    You initialized the variables as false: static boolean a,b,c;
    Then, as previously noted, the || operator did not evaluate the last 2 conditions.
    To get what you expected, use the non-short-circuiting versions:
    Opr     Use                Returns true if
    &&      op1 && op2      op1 and op2 are both true, conditionally evaluates op2
    ||      op1 || op2      either op1 or op2 is true, conditionally evaluates op2
    &      op1 & op2      op1 and op2 are both true, always evaluates op1 and op2
    |      op1 | op2      either op1 or op2 is true, always evaluates op1 and op2

  • Behaviour of post increment/decrement operator

    int i = 1;
    i = ++i;
    System.out.println( i ); //output is 2
    i = i++;
    System.out.println( i ); // output is 2, WHY?

    Well, it seems that you didn't get the point at all.
    I know how to do the increment operation. What I
    intended to know is the behavior in this scenario.
    And you got that in reply 2.I assumed the answer to be that. but i was only trying to be sure.
    I know that such codes r not in common use and they are meaningless too, but such codes do come up in various quizzes, etc. to test ur knowledge. we always learn WHAT not to do, but we seldom try to know WHY not to do it. in our endeavor to learn advanced topics we tend to ignore the basics.
    Coming back to the original code can someone tell me whether this is a well defined behavior unlike c/c++ where the behavior of such codes are undefined. as far as i know java is a strongly typed language, where ambiguities have been eliminated (believe i am not wrong on this). Can i expect the same results on all compilers??
    and i hope that the forum behaves in a sane manner in future. Instead of blatantly dismissing a post, let people give reasons for it.
    Thanks

  • Please help me to understand operator precedence and associativity

    I am trying to run following code:
    long i = 10;
    long k = ++i + i - i - --i ; // here i is pre incremented and decremente
    System.out.println(k);
    gives output: 4
    and
    long i = 10;
    long k = i++ + i-- - i-- - i-- ; // here i is post incremented and decremente
    System.out.println(k);
    gives output: 2
    Please give me the steps of each evaluation
    I mean how this gives output value:
    any suggesion highly appreciated

    I am trying to run following code:
    long i = 10;
    long k = ++i + i - i - --i ; // here i is pre
    incremented and decremente
    System.out.println(k);
    gives output: 4
    and
    long i = 10;
    long k = i++ + i-- - i-- - i-- ; // here i is post
    incremented and decremente
    System.out.println(k);
    gives output: 2
    Please give me the steps of each evaluationNo one in their right mind would ever write code this way.
    Looks like a certification or homework problem.
    >
    I mean how this gives output value:
    any suggesion highly appreciatedI'd suggest that you read the precedence rules and go through these very carefully.
    %

Maybe you are looking for

  • Is it possible to use an iMac as an external monitor for a MacBook?

    What is the process (if any) to turn off the iMac's system and make it essentially an external monitor for the MacBook?

  • Print form fields ONLY in Adobe Reader XI.

    I created a form in LiveCycle for use by an admin (who only has Adobe Reader, not Acrobat) to print checks. I want to print form fields ONLY. Is there a way to do this? HELP!

  • Touchpad E520 replacement?

    The touchpad is not working, does not recognize mouse movement nor left-right click and confirmed its not disabled, can the defective part be replaced and if so where might I purchase it?

  • Can't boot up from install disc

    Install disc shows on the desk top and in restart under system preferences but will not restart the Mac, I have also tried holding the "c" down on start up but nothing happens though I can hear the drive spinning. Is there some way I can get informat

  • Configuring System DSN for UCCX8

    Hi, I was just about to post a query re. configuring the System DSN for wallboards in UCCX 8. I followed the instructions on pages 461-463 of the document below: http://www.cisco.com/en/US/docs/voice_ip_comm/cust_contact/contact_center/crs/express_8_