This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
I have verified the following statements and results: float f1 = 1.0 --> compile error byte b1 = 2 --> compiles and runs byte b1 = 129 --> compile error I understand that a literal of: 1 --> is interpreted as an int 1.0 --> is interpreted as a double and further, that 'downcasting' requires a 'cast' opertion. Why then, does the statement: byte b1 = 2 not generate a compile error also?
In the case that you use a literal to initialize a variable smaller than an int (in this case, a byte), the compiler will check to see if that literal is within the range of the variable and only cause a compiler error if the value is out of range. This is why, when yo assign the value 1 to a byte, it works and when you assign 128 to a byte, it fails (128 is outside the valid range of a byte). Java does the same thing with final variables. This code causes a compiler error:
In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied: - The expression is a constant expression of type byte, short, char or int. - The type of the variable is byte, short, or char. - The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
Just for formality, from Sun's Java tutorial: "A series of digits with a decimal point is of type double. You can specify a float by putting an 'f' or 'F' after the number."
byte b1 = 129 --> compile error
Ditto with Corey and Valentin. But let's just reminisce about the basics: how do you determine the range? Since a byte has a size of 8 bits, you can determine it manually by multiplying 2 (a bit has 2 possible values, "1" or a "0", or "true" or "false") eight times (or 2 raised to the power of eight), which equals 256. Thus the range of values for the byte data type is -128 to 127 inclusive, which does not include 128. Why just 127? because you have to sneak in the special number "0" to the range (...,-1, 0, 1,...). Ex Animo Java! -- Val [ April 17, 2002: Message edited by: Val Pecaoco ]
"Knowledge is power, but enthusiasm is the key." -- Lavern Barn