|
|
Language Fundamentals - Numeric Literals
- numeric constants are written using literals
Integer literals
- Integer constants are strings of octal, decimal, or hexidecimal digits
decimal base 10 10
octal base 8 010 (8) // preceded by a zero
hex base 16 0xA (16) // preceded by 0x
- Integer constants are long if they end in l or L
32l or 32L // capital L recommended use
- if an int literal is assigned to a short or a byte and it's value is within legal range, the literal is assumed to be a short or a byte.
byte b = 5; // assumed to be a byte
short s = 32500; // assumed to be a short
short sh = 50000; // illegal
- In all other cases you must explicitly cast when assigning an int to a short or byte. (JPL pg 108)
int i = 5; // declared and initialized int
byte b; // declared byte
b = i; // causes compile error
b = (byte)i; // compiles
Floating-point literals JPL pg 108
- floating-point numbers are expressed as decimal numbers with an optional decimal point
Examples of valid floating-point numbers:
0.10
1.
.0001
1.8e1 // 'e' = exponential
- at least one digit must be present
- floating-point constants are double values unless they are suffixed with an f or F
- if a d or D suffix is used they are double values
10.5 // assumed double value
10.5F // float value
- a double constant cannot be assigned to a float variable even if the double is within the float value range; however, a double can be cast as a float
double d = 3.213; // double constant
float f;
f = d; // compile error
f = (float)d; // compiles
Traps
- assigning a non-integer literal to a byte, short or character
- assigning a double literal to a float
|