• Post Reply Bookmark Topic Watch Topic
  • New Topic

Precedence of assignment operators. (Sybex)  RSS feed

 
harsh asnani
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As stated in the study guide just above the table on page 52, "If two operators have the same level of precedence, then Java guarantees left-to-right evaluation. However, its not the case with assignment operators.

System.out.print(3/2/2) must print 0 if L-R evaluation is guaranteed. It prints 1.

String t="a";
String s="b";
String x=s+=t+="1";
System.out.println(x);
prints ba1 while b should have been printed if again, L-R evaluation is guaranteed.

By speculation, it seems R-L is guaranteed for assignment operators.
 
harsh asnani
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.print(3/2/2) must print 0 if L-R evaluation is guaranteed. It prints 0(not 1)Sorry!
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 36659
475
Eclipse IDE Java VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

For your assignment example, it is still left to right but confusing.

String x=s+=t+="1";

Here's what Java is "thinking"
1) s becomes the current value of s ("b") plus the value of t. But wait we don't know the value of t yet.
2) t becomes the current value of t ("a") plus "1". So t is now "a1"
3) Ah. Now we can complete s which is "ba1"
4) Assign that to x
5) print it out
 
Henry Wong
author
Sheriff
Posts: 23030
120
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
harsh asnani wrote:As stated in the study guide just above the table on page 52, "If two operators have the same level of precedence, then Java guarantees left-to-right evaluation. However, its not the case with assignment operators.


First, if two operators have the same level of precedence, then Java uses Associativity to determine which one has the higher "precedence". In this case, assignment operators have right to left associativity, so, this ...is equivalent to this...
Second, Evaluation order, Precedence, and Associativity, are *not* the same thing. As Jeanne explained, Evaluation order is left to right regardless of precedence and/or associativity. See ... https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!