File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Expression - How 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 "Expression - How" Watch "Expression - How" New topic
Author

Expression - How

susan waters
Ranch Hand

Joined: Feb 21, 2006
Posts: 68
can anybody explain me how it print -9?


thanks
[ July 19, 2006: Message edited by: Barry Gaunt ]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

You've got to understand the priority of each symbol, and put brackets around them:
x -= ( (1 < 0)?2:4 );

1 < 0 ? No -> 4
x = x - 4
x = -9

Here is nice table illustrating operators precedence:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html

You'll notice that -= is lower than "? :"
[ July 18, 2006: Message edited by: Satou kurinosuke ]

[My Blog]
All roads lead to JavaRanch
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The expression 1 < 0 ? 2 : 4 is an expression whose value is 2 if the condition is true, and 4 if the condition is false.

Since the condition is false, the value of the expression is 4.

x is -5.

When you execute the line x -= 1 < 0 ? 2 : 4, that is like saying x -= 4, so x is -9.
[ July 19, 2006: Message edited by: Barry Gaunt ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Expression - How