jQuery in Action, 3rd edition
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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 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: http://aspose.com/file-tools
subject: Java operators
It's not a secret anymore!