File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes More question ... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "More question ..." Watch "More question ..." New topic

More question ...


Joined: Jan 17, 2002
Posts: 4
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

Joined: Aug 26, 2001
Posts: 7610
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
[ January 17, 2002: Message edited by: Valentin Crettaz ]

[Blog] [Blogroll] [My Reviews] My Linked In
Seany Iris
Ranch Hand

Joined: Jan 08, 2002
Posts: 54
Which result will be printed,the result of the expression or the result of variable a? I am confused.

help you means help me
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059
The result of each expression will be printed.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
I agree. Here's the link:
subject: More question ...
jQuery in Action, 3rd edition