when is it necessary to use suffix of literals?

X

xian_hong2046

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
 
D

Diomidis Spinellis

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.

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);
 
X

xian_hong2046

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
 
D

Diomidis Spinellis

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.
 
R

Roedy Green

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top