This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Java operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java operators" Watch "Java operators" New topic

Java operators

Jackk Ripper

Joined: Apr 12, 2007
Posts: 1

I have this piece of code:
class Test {
public static void main(String s[]) {
int a = 1;

a = 2 + a + a++ + 3;
a = 1;
a = 2 + a++ + 3 + a;

The output is:

Shouldn't the values be equal? I thought that values for all variables are first retreive. Then the unary operators are applied. Then lastly, the binary operators are applied from left to right. Please help.

Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710
Hi Ripper,

Welcome to JavaRanch,

--> Left to right operation
a++, a is incremented after it is used.
int a=1;
a = 2 + a + a++ + 3;

a = a + 1 + 1 + 3=7;

(Simply understand in the way: You are assigning the resultant to the a itself, so incremented a goes lost)

a = 2 + a++ + 3 + a;
a = 2 + 1 + 3 + 2=8;

Got it?


marc weber

Joined: Aug 31, 2004
Posts: 11343

"Jackk Ripper,"

Welcome to JavaRanch!

Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use real (or at least real-looking) names.

You can edit your display name here. Thank you for your prompt attention!


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: Java operators
It's not a secret anymore!