long

In Java, a long is a primitive data type that is used to store whole numbers, which can be either positive or negative. It has a fixed size of 64 bits (8 bytes), meaning it can hold much larger values than other integer types like int. It can store numbers:

  • From: -9,223,372,036,854,775,808
  • To: 9,223,372,036,854,775,807

Example of using long

long count = 100L;   // Correct way to declare a long (use the L suffix)

When to use long:

  • Use long when the value exceeds the range of an int (which is from -2147483648 to 2147483647)
  • For example, very large numbers like population counts, financial transactions, or timestamps

Primitive type

A long is a primitive type. This means that it directly stores the value in memory, not a reference to the value. If you change the value of a long variable, the old value is replaced by the new:

long a = 15L;  // 'a' is 15
a = 20L;       // Now 'a' is replaced by 20

Long wrapper class

Even though long is a primitive type, there’s a corresponding wrapper class called Long This class provides useful methods to work with long values.

Useful Long constants

ConstantExampleResult
MAX_VALUELong.MAX_VALUEReturns largest possible long value (9223372036854775807)
MIN_VALUELong.MIN_VALUEReturns Smallest positive long value (-9223372036854775808)
SIZELong.SIZEReturns size of a long in bits (64)
BYTESLong.BYTESReturns size of a long in bytes (8)

Converting values

Converting numeric String to long. If the String is not numeric (e.g. "hello"), Java throws a
NumberFormatException.

long num = Long.parseLong("12345"); // Returns 12345

Converting a long to a String

String text = Long.toString(12345L); // Returns "12345"

Comparing Long values

compare(long a, long b)

int result = Long.compare(12345L, 23456L);

compareTo(Long other)

Long x = 12345L;
Long y = 23456L;

x.compareTo(y);

Both compare and compareTo return these values:

  • 0 → if values are equal
  • -1 → if first is less than second
  • 1 → first is greater than second

equals(Object obj)

Long x = 12345L;
Long y = 12345L;

x.equals(y); // true

Math helper methods

MethodExampleResult
max(long a, long b)Long.max(12L, 15L)Returns the larger value
min(long a, long b)Long.min(12L, 15L)Returns the smaller value
sum(long a, long b)Long.sum(12L, 15L)Returns the sum of the two values

Summary

  • Long stores whole numbers using 64 bits (8 bytes)
  • Must use L suffix when assigning values
  • It’s a primitive type
  • Use Long wrapper class methods for conversions, comparisons, and constants
  • Prefer int unless you need long

Further Reading


Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories