• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

More question ...

 
amatya
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int a=4, b=6;
System.out.println(a---b); //Answer: -2
System.out.println(a+-b); //Answer: -3
System.out.println(a- -b); //Answer: 9
System.out.println(a+ +b); //Answer: 9
Anybody with CLEAR explanation why?
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah tricky !!
The 1st line explains the others. The expression a---b will be evaluated as (a--) - b which is 4 - 6 = -2. BUT THEN a is decremented (a--) and the value of a is now 3.
The rest is now straightforward:
The second expression gives a + (-b) which yields 3 + (-6) = -3.
The third expression gives a - (-b) which yields 3 - (-6) = 9
And the last expression gives a + (+b) which yields 3 + (+6) = 9
I think the trickiest part was the first expression with the three minus signs one after another (---). Here is the thing, the Java parser always takes the longest accepted token when parsing, that is, --- when parsed gives the token -- (decrement operator) and - (minus).
Please change your name according to the Javaranch Naming Policy
HIH
[ January 17, 2002: Message edited by: Valentin Crettaz ]
 
Seany Iris
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which result will be printed,the result of the expression or the result of variable a? I am confused.
 
Marilyn de Queiroz
Sheriff
Posts: 9066
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The result of each expression will be printed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic