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);

Similar Messages

  • (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.

  • 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.

  • 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)

  • Postfix incrementer with assignment operator

    Hi all,
    we tried the following code,
    byte b=14;
    b=b++;
    sop(b);and we expected 15 as output but we got 14.
    as we learned the statement
    b=b++;
    is the grouping of two statements
    b=b;
    b++;
    if we use the same two statements we are getting 15.
    if we assign to another variable it works fine.
    and we are sure that the statement b=b++ is correct logically and should increase the number.
    we are seeking your openions on this issuue.

    As pointed out already this topic has been done to death. Pity you didn't search first.
    Anyhow, what value will be output in the following code?
    int b = 14;
    int c = b++;
    System.out.println(c);Hopefully your answer will be 14. So if the result of this code is 14 why should it be 15 as you exepct when it is b = b++?

  • 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

  • Prefixing and auto-increment field

    Hello
    I have a web application (php/mySQL) that has an auto-increment primary key field called job_id.
    Could anyone help me add a prefix to this?
    I want to add the year and month (YYMM/) in front of the field (e.g. 0811/1234 then 0811/1235 assuming current month and year is Nov 2008).
    Maybe Im wrong about adding the prefix to the primary key. Should I maybe add an additional field to maintain this?
    Any advice greatly appreciated...
    Regards
    Paul

    Hi Paul,
    MySQL table and column names may only consist of letters, underscores and numbers anyway, so the date format you´d like to use would lead to errors due to the forward slashes.
    Maybe Im wrong about adding the prefix to the primary key.
    I don´t know what you want to achieve with this approach, but I´d really leave the name of the Primary Key column "as is" and use a different column for storing data which contains such date values.
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • 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.
    %

  • 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

  • Operator precedence

    Hello,
    I was going through someone else's code today, and found something I didn't quite understand. The code fragment is as follows:
        for (int j = 0; j < count / 2; j++)
            k = j + 1;
            for (m = 0; m < height; m++)
              for (n = 0; n < width; n++)
                arrayOfInt[j][(m * width + n)] = imgpixels[(m / k * k)][(n / k * k)];
            (snip)
          }Now, most of it, I think I understand, apart from the line:
    arrayOfInt[j][(m * this.width + n)] = imgpixels[(m / k * k)][(n / k * k)];
    - how is Java interpreting the algebra in the square brackets? For the first set of square brackets, is it [m/(k*k)] or is it [m*k/k]? This latter one doesn't make any sense, as the k's would cancel leaving just m.
    I've looked at precedence of the operators and found that *, / and % are given equal precedence, so what is going on here?

    875465 wrote:
    - how is Java interpreting the algebra in the square brackets? For the first set of square brackets, is it [m/(k*k)] or is it [m*k/k]? This latter one doesn't make any sense...Probably because it isn't possible.
    Java will never re-order operators, it will only use predecence to evaluate one set before another, so in the case above the only two possible interpretations are:
    <tt>(m / k) * k</tt>   or
    <tt> m / (k * k)</tt>
    In fact it will use the first, because * and / have the same precedence, so evaluation works from left to right, which indeed looks like a roundabout way of saying 'm'.
    However, since we don't know what the types of n, m, and k are, it's difficult to speculate what the effects are; it could also be a roundabout way of saying 'nearest multiple of k'.
    On the other hand, it could also be
    1. It's a horrible piece of code (my opinion).
    2. They actually intended it to be <tt> m / (k * k)</tt>.
    Which is why it's usually a good idea to explicitly bracket your code and remove all doubt. The only place that sort of stuff belongs is in SCJP tests.
    Winston

Maybe you are looking for

  • At end of and sum key word is not working properly

    Hi All, I have a requirement in that I have to calculate at the end of each fiscal year. I am using this section of code, But in my output its only showing me the value of the last record, its not summing up at the end of fiscal year. This is my sect

  • How do I send a text file from one device to another?

    Hi, I'm working on an Android Air app made in CS5.5 where user data is saved in the app's applicationStorageDirectory as a text file. Is there a way to send this saved text file to another device's applicationStorageDirectory via Bluetooth/email/text

  • Very Slow preview rendering for lightroom 5 on import

    I am seeing very very slow rendering of preview images only when using the import function in lightroom 5. By slow, I mean for a shoot of 60 shots in raw, it could take 30 minutes before I can preview them all in the pane to see which ones I want to

  • Problem with N8

    I am facing one problem with Nokia N8. I brought this New Nokia N8 phone from US to India so it is not at all functioning nor responding anything. When I tried to Switch ON this phone it is not responding anything.  Can anybody suggest me what should

  • Trying to compare date columns with differing formats...

    I have an app that created a series of tables via ODBC using ANSI standard datatypes. For most, this isn't a problem, but one in particular is driving me crazy: TIMESTAMP. In Oracle, it shows up as a TIMESTAMP(6). I don't want to mess with the app's