Hello,
I'm a bit confused about when to use trailing characters such as "L",
"F" and "D" for literals. For example, if I have a double, then
naturally I'll have something like:
double j = 42;
Then why would I bother to use
int j = 42D;
Similarly for other trailing characters.
Many thanks,
xian
Diomidis Spinellis - 12 Apr 2006 13:44 GMT
> Hello,
>
[quoted text clipped - 9 lines]
>
> Similarly for other trailing characters.
You use the trailing suffixes when you want to force a calculation to be
performed with the corresponding data type. For example:
// Will print 0, because the result overflows a 32-bit int.
System.out.println(0x80000000 * 0x100);
// Will evaluate the result as a long and print 549755813888
System.out.println(0x80000000L * 0x100);

Signature
Diomidis Spinellis
Code Quality: The Open Source Perspective (Addison-Wesley 2006)
http://www.spinellis.gr/codequality?cljp
xian_hong2046@hotmail.com - 12 Apr 2006 14:19 GMT
I see, so does it mean the trailing suffixes are only used when the
literals are not assigned to any variable? Because if the literals are
assigned to some variables, the types of the variables (long, double)
should tell the compiler how much memory should be allocated to the
values. Is this right?
Thanks a lot!
xian
Diomidis Spinellis - 12 Apr 2006 14:38 GMT
> I see, so does it mean the trailing suffixes are only used when the
> literals are not assigned to any variable? Because if the literals are
> assigned to some variables, the types of the variables (long, double)
> should tell the compiler how much memory should be allocated to the
> values. Is this right?
Assignment to a variable is not relevant. For example, the following
code will still print 0.
int i = 0x80000000 * 0x100;
System.out.println(i);
What the trailing suffixes do is to FORCE the EVALUATION of an
expression to use the specific type.

Signature
Diomidis Spinellis
Code Quality: The Open Source Perspective (Addison-Wesley 2006)
http://www.spinellis.gr/codequality?cljp
Roedy Green - 12 Apr 2006 19:20 GMT
On 12 Apr 2006 05:27:17 -0700, "xian_hong2046@hotmail.com"
<xian_hong2046@hotmail.com> wrote, quoted or indirectly quoted someone
who said :
>I'm a bit confused about when to use trailing characters such as "L",
>"F" and "D" for literals. For example, if I have a double, then
>naturally I'll have something like:
the safest thing to do is put a trailing D on all doubles, an
trailing F on all floats and a trailing L on all Longs.
Yo would not write
int i = 42D:
since you don't mean a IEEE double. You mean an int.
you would write
double d = 42D/43D;
because you want them to be treated as doubles and the division to be
done fractionally.

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.