From | To |
byte short char int long float | short, int, long, float, double int, long, float, double int, long, float, double long, float, double float, double double |
long num = 123456789; int i = num; | This will produce an error because going from a long to an int is a narrowing conversion. | |
int value = 300; byte b = (byte)value; println(b); | This will give output of
| |
long num = 4294983648L; int i = (int)num; println(i); | Note that for a very large integer constant you need to add the letter L (either lower-case or upper case) to the end of the constant. This number is too large to fit in an int so only part of the number can be stored. The output is
| |
int i = 12345; float f = i; | These statements are legal since this is a widening conversion |
You can use a cast to convert from real values to integer values. The numbers after the decimal will be truncated (dropped). Note that the decimals are simply dropped, no rounding occurs.
Program | Output | |||
|
|
Literal Constant | Type |
"Pamela Wallin" | string |
25 | int |
0.13 | float |
You can also use named constants. You declare a named constant like a variable except that you include the keyword final in front of the declaration. This can make you program easier to read. Using the identifier TAX_RATE instead of the literal 0.l3 makes things clearer. Using named constants will also make it easier to modify your program in the future. Suppose the tax rate changes. Instead of trying to track down the many places you may have used the literal 0.13 in your program you only need to change the one line where you declared the constant. Since you are only making one change, your changes will be more reliable as well. With the short programs we've used so far, using named constants might not seem that important. But when your program get very large you'll be glad you went to the trouble of using named constants. To replace the literals in the above example we could write the following code:
|
|