File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java operators

 
Jackk Ripper
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic