0
public class MainClass
{

     public static void main(String[] args)
     {
        int i = 13 - - 14 + + 15;
        // evaluate this as Right to Left associativity 
        // so (13 - (-14)) + + 15 = 27 + +15 = 42 --> correct 
        System.out.println(i);
     }
}

Since + and - has same precedence , so it will have right to left associativity. So I thought that any expression like 13 - - 14 + + 15 will be considered as 13 - (-14 + + 15) and output will be 12, but output is coming 42. Can anyone please explain the output?

3
  • 1
    Left-to-right associativity means that A op B op C is (A op B) op C, not A op (B op C). Commented Apr 3, 2015 at 11:12
  • Thanks Oliver!! I have edited the question. + and - operator has right to left associativity. Commented Apr 3, 2015 at 11:54
  • 1
    The unary operators are right-to-left; the binary operators (i.e. addition and subtraction) are left-to-right. Commented Apr 3, 2015 at 11:56

3 Answers 3

2

You can look at 13 - - 14 + + 15 like 13 - (-14), which is like 13 + 14, which is 27, followed by + (+ 15), which is like + 15, which equals 42.

Sign up to request clarification or add additional context in comments.

Comments

1

If you evaluate the expression from left to right (as Java does), you start with 13 - - 14 which is the same as 13 - (-14), which is 27. 27+ +15 is 42.

Comments

0

Evaluating from left to right it's 13 - (-14) + (+15) so 13 + 14 + 15 = 42

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.