• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Operators & Assignments

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I have found the following question in one of the SCJP test engine on
"Operators & Assignments" topic

Q: In Java all operands are evaluated left to right, even if the order
of execution of the operations is something different.....

The answer for the above question is true.

What does it mean? Does it mean, in java all operands are evaluated left to
right irrespective of the precedence ..? if so

System.out.println(14+6/2) output must be 10(according to left
to right) but it is giving as 17(according to precedence)

Can you explain this?
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In this case, the operands are literal values that "evaluate" quite simply to 14, 6, and 2. Then the operations are performed according to operator precedence: 6/2 added to 14.

But what if the operands weren't literals? Suppose this was x + y/z instead. Then the operands x, y, and z would each need to be evaluated to a numeric value before any operations are performed.

Do you see the distinction?
[ March 17, 2005: Message edited by: marc weber ]
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's look at the steps to evauate "x + y/z" closely, assumning a pure push-down stack CPU architecture.

1. get the value of x and push it onto the stack
2. get the value of y and push it onto the stack
3. get the value of z and push it onto the stack
4. pop the last two entries from the stack, divide them, and push the result onto the stack.
5. pop the last two entries from the stack, add them, and push the result onto the stack.

As you can see from this example, the order in which operands are evaluated and the order in which operations are performed on those operands are two different matters.
 
Sunglasses. AKA Coolness prosthetic. This tiny ad doesn't need shades:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic