Initialize a long in Java
To initiate a long
in Java, suffix the literal number with 'L':
Working with gigantic values exceeding int bounds? Declare it with 'L'!
Beware! Omitting L
may summon the evil compile-time errors for exceeding int
bounds.
When long comes in handy
Use long
when your numerical data outpaces the speed limit of int
(32-bit), and you need a wider highway (64-bit). Ideal for large distances, precise timestamps, or storing the number of times you've rolled your eyes at work today!
Common gotchas
Ghost of the missed 'L' suffix
If you're dealing with numbers bigger than int
and forget to put the L
suffix, Java might treat your number as int
resulting in a loss of data or Numeric Overflow.
The tricky lowercase 'l'
While a lowercase 'l' is correct, it's a confusing troublemaker looking like the number 1
. For clarity, always go for an uppercase L
.
Comparing data types
int vs long
- ‘int’ is the thrifty choice for smaller ranges, memory-efficient.
- ‘Long’ is the heavy lifter for larger numerical ranges and precise calculation.
Auto-magic type conversion
When assigning an int
to a long
, Java kindly upgrades it for you.
But Java expects a "Please" when downgrading: explicit casting is needed when narrowing a long
to an int
:
Best practices and potential pitfalls
Enhancing readability of long values
Underscores _
can be your best friend when dealing with long numbers for better readability:
Casting woes
Cast carefully! A long
shrunk to a float
or a double
might lose precision:
Bigger than long
For values larger than long
, consider using java.math.BigInteger
.
Was this article helpful?