Explain Codes LogoExplain Codes Logo

Initialize a long in Java

java
data-types
best-practices
casting
Nikita BarsukovbyNikita Barsukov·Nov 26, 2024
TLDR

To initiate a long in Java, suffix the literal number with 'L':

long luckyNumber = 7L;

Working with gigantic values exceeding int bounds? Declare it with 'L'!

long astronomicalNumber = 9223372036854775807L; // "This number is so big even Jeff Bezos can't afford it!"

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.

// Incorrect - Treated as int and too large, results in compilation error long tooBigForInt = 2147483648; // Correct long fitsInLong = 2147483648L;

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.

// Confusion Alert! long smallL = 1000l; // "Is it 10001 or 1000L?" // Clear and readable long clearL = 1000L;

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.

int smallNumber = 100; long largerContainer = smallNumber; // Look Ma, no cast!

But Java expects a "Please" when downgrading: explicit casting is needed when narrowing a long to an int:

long largeNumber = 100L; int smallerContainer = (int) largeNumber; // Explicit casting required

Best practices and potential pitfalls

Enhancing readability of long values

Underscores _ can be your best friend when dealing with long numbers for better readability:

long creditCardNumber = 1234_5678_9012_3456L; // Now that's better, isn't it?

Casting woes

Cast carefully! A long shrunk to a float or a double might lose precision:

long preciseValue = 123456789123456789L; double approxValue = (double) preciseValue; // Precision - "I don't feel so good."

Bigger than long

For values larger than long, consider using java.math.BigInteger.

BigInteger reallyMassiveNumber = new BigInteger("1234567891011121314151617181920"); // "This number just broke my calculator!"