This week's giveaway is in the Groovy forum. We're giving away four copies of Groovy Fundamentals video training course and have Ken Kousen on-line! See this thread for details.

Alex Birmingham wrote:Why do the following two lines of code equate to 0, vs 5.7 or 5?

System.out.println((12 / 21) * 10);

- and -

int = (int) ((12 /21) * 10);

Please read about "BODMAS". I am sure you will find your answer yourself.

- (12 /21) -- return 0.57 which is converted to 0 because it is int calculation by default.
- Then 0 will be multiplied by 10 which equals to 0.
- Therefore the answer will be Zero (0)

Note:
- If you change your code to......

System.out.println((12.0 /21) * 10);

Then the result will be what you were expecting.........

Alex Birmingham wrote:Ah!!! I didn't realize that Java treated numbers as specific primitive types before we assign them variables and therefore cast them.

Now I know why l or L must be added to longs, and f or F to floats.

Much appreciated.

Just remember that in arithmatic calculations such as that all types are promoted to the largest type in the calculation. So in the following code all numbers are promoted to a double.

Also take notice that if you are going to assign that value to a variable you may need an explicit cast (if the cast is to a smaller primitive type) like so:

Even though the value is small enough to fit in an int, technically, the value is going to be a double and it cannot be directly placed in an int without an explicit cast.

SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."

W. Joe Smith wrote:Just remember that in arithmatic calculations such as that all types are promoted to the largest type in the calculation.

But they are never smaller than int. For instance:
But:

Also take notice that if you are going to assign that value to a variable you may need an explicit cast (if the cast is to a smaller primitive type) like so:

Surely you mean
Casts go for mathematical operations, so your example would cast 4.5 to int (making it 4), then adding 5.6 to make the result 9.6, which is a double.

W. Joe Smith wrote:Just remember that in arithmatic calculations such as that all types are promoted to the largest type in the calculation.

But they are never smaller than int. For instance:
But:

Also take notice that if you are going to assign that value to a variable you may need an explicit cast (if the cast is to a smaller primitive type) like so:

Surely you mean
Casts go for mathematical operations, so your example would cast 4.5 to int (making it 4), then adding 5.6 to make the result 9.6, which is a double.

True. This is why I should never post before I drink at least 1 cup of coffee.