aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes operators and precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "operators and precedence" Watch "operators and precedence" New topic
Author

operators and precedence

Leandro Oliveira
Ranch Hand

Joined: Nov 07, 2002
Posts: 298
about this:
int a=1;
int b=2;
String s= b+a-- +((b=(b+10))+" "+a++);
System.out.println(s);
don't u think it should appear "1412 1" on the screen???
Because:
first ((b=(b+10))+" "+a++) will be evaluated
then b=(b+10) will be evaluated and result in 12
then it will be 12+" " + a++
then a++ will be evaluated and result in 1
all will be, then, "12 1"
then a-- will be evaluated and result in 2
then b + a will be evaluated and result in 14
then 14+"12 1" will be evaluated and result in "1412 1"!!!
BUT IT DOES NOT HAPPEN THIS WAY THE END RESULT IS "312 0" WHY???
Sridhar Srikanthan
Ranch Hand

Joined: Jan 08, 2003
Posts: 366
Dear leandro,
String s= b+a-- +((b=(b+10))+" "+a++);

b=2 , a =1
a couple of points to remember
  • Java evaluates an expression from left to right
  • If there is a string on either side of the "+" operator, the other operand is converted to a string
  • ++ and -- if applied as prefix like ++a increment the value of a immediately
  • ++ and -- if applied as suffix like a++ increment of the value happens in the next expression using the opearnad(i,e a)


  • now,
    a = 1;
    b=2;
    String s= b+a-- +((b=(b+10))+" "+a++);
    as java evaluates from left to right , the above expression is calculated as
    s = (b=2) + (a--) + ((b=12)+" " + (a++));
    b=2 is because left-to-right evaluation
    a-- evaluates to 1 and changes a to 0 after a-- is used.
    similarly a++ (as a has become 0 because of previous expression) is zero but after this expression, increments by 1.
    so finally
    s = (2+ 1 + (12+" "+0));
    => s = (3 + (12 0);
    => s = 312 0;
    Hope this helps
    Sri
    b+ a-- + (
    [ February 15, 2003: Message edited by: Sri Sri ]
    Leandro Oliveira
    Ranch Hand

    Joined: Nov 07, 2002
    Posts: 298
    thanks!!! u are right!!! I did not pay atention to the left to right evaluation of things!!!
     
    I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
     
    subject: operators and precedence
     
    Similar Threads
    array confusion
    Operator precedence and associativity confusion........
    Arrays & Promotions
    Question from K&B Book
    post increment operator