aspose file tools*
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java operators" Watch "Java operators" New topic
Author

Java operators

Jackk Ripper
Greenhorn

Joined: Apr 12, 2007
Posts: 1
Hi

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

a = 2 + a + a++ + 3;
System.out.println(a);
a = 1;
a = 2 + a++ + 3 + a;
System.out.println(a);
}}

The output is:
7
8

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.

Ripper
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
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=1;
a = 2 + a++ + 3 + a;
a = 2 + 1 + 3 + 2=8;


Got it?

Regards,
cmbhatt


cmbhatt
marc weber
Sheriff

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!

-Marc


"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
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java operators