Roel De Nijs wrote:When executing calculations Java uses a "standard" datatype. When you are calculating with integers, the result of the calculation will be an int. That's why for example this code snippet won't compile (although you might think it would, it really doesn't ):
If you are doing some calculation with floating-points (decimals), the result will be a double. Again the reason why this won't compile too:
Also don't forget: when you use a floating-point literal value, it's automatically considered to be a double too. That's why you need to add an f (or F) when you need a float. So float f = 10.0; will not compile, but float f = 10.0F; does!
In your println-statement you are adding an int with a double, so the result will be a double (and thus 3.0 is printed)
Hope it helps!
Robert Liguori wrote:Fantastic question, associated with "Binary Numeric Promotion"!
You will find the answer here:
The Java Language Specification, Java SE 8 Edition
http://docs.oracle.com/javase/specs/jls/se8/jls8.pdf (5.6.2 Binary Numeric Promotion)
"...If either operand is of type double , the other is converted to double ..."
Note: I also have this reference in the Java 8 Pocket Guide.
Roel De Nijs wrote:What do you think will happen with this code snippet? Compiles without error or compiler error (or something else)?
Ed Cardenas wrote:But after I tried to compile it, there was no error. How did that happen?
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int: - A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Roel De Nijs wrote:
So if you now know all this extra info, what would happen with this code snippets?
Ed Cardenas wrote:Isn't the expression promoted to a compile time constant?