Jump to content

Advanced Java/Declaring float and long Literals

From Wikiversity

A Quick Review

[edit | edit source]

A literal is an expression that represents a constant value. For example, a char literal is always surrounded by two single-quotes: 'c'.

Numeric literals are simpler: just type in the number. For example, to instantiate an int with the value of four, you know to type

int foo = 4;

By default, a numeric literal is considered as an int type by the JVM if it doesn't have a decimal point. Otherwise, it's considered a double.

floats and longs

[edit | edit source]

To specify a numeric literal as a long instead of an int, add an L (for long) to the end of the literal. Either capital or lowercase will work, but a lowercase 'l' can easily be confused with the numeral '1', especially in monospace fonts.

long bar = 2974802746820L;

To specify a numeric literal as a float instead of a double, add an F (for float) to the end of the literal. Again, either capital or lowercase will work.

float bam = 2.71828f;
float baz = 3.14159F;

Why Does This Matter?

[edit | edit source]

Since a double is longer than a float, and thus can hold more significant digits, the compiler will complain if you try to stuff a double value into a float variable. If you're defining a variable with a literal value, you can tell the compiler that you really do want a float by using the F suffix.


Project: Advanced Java
Previous: None — Advanced Java/Declaring float and long Literals — Next: Bitwise Operators