Seeing that there are only so many ways to represent a number in your program, Java developers had to select and assign each form to the most common use case. For those forms that are selected by default, a suffix that indicates the exact type is optional.
- For integer literals (int, long), the default value is int. For obvious reasons.
- For floating point literals (float, double), the default value is double. Since using double potentially allows safer arithmetic to stored values.
So, when you enter 12 into your program, it is int literal, as opposed to 12L , which is long. And when you type 12.3 , it is a double literal, not 12.3F , which is a float.
So where is this relevant? First of all, when processing down-converting or narrowing conversions. Whenever you omit a long path to int or double-float, there is a possibility of data loss. Thus, the compiler will force you to indicate that you really want to narrow the conversion, signaling a compilation error for something like this:
float f = 12.3;
Since 12.3 is a double, you have to explicitly pass it to a float (basically, by subscribing to narrowing the conversion). Otherwise, you could indicate that the number is indeed a float using the correct suffix;
float f = 12.3f;
So to summarize too much, you need to specify a suffix for longs and floats - this is a compromise that the language developers have chosen to balance the need to specify what exactly such a number is, with the flexibility of converting numbers from one type of storage to another.
Perception Mar 17 '12 at 10:13 2012-03-17 10:13
source share