Java Long Class: Methods, Parsing, Conversion, Constants and Examples

0

The Long class is the wrapper class for Java's primitive long type. It represents whole-number values that require a much larger range than int can provide.


You will commonly encounter Long when working with timestamps, database identifiers, file sizes, counters, large numeric values, and APIs that require objects instead of primitive values.


Remember: long is a primitive type, while Long is its corresponding wrapper class.

Why Do We Need Long?

An int uses 32 bits and has a limited range. When an application needs to represent a much larger whole number, the primitive long is a better choice.


The Long wrapper becomes useful when that large number must participate in an object-oriented API, collection, or generic type.


List<Long> ids = new ArrayList<>();

ids.add(10000000001L);
ids.add(10000000002L);
ids.add(10000000003L);

The L suffix tells Java that the numeric literal should be treated as a long. Java then autoboxes those primitive values into Long objects when adding them to the collection.


Range of the Long Type

A Java long is a signed 64-bit integer. Its range is significantly larger than that of int.


System.out.println(Long.MIN_VALUE);
System.out.println(Long.MAX_VALUE);
System.out.println(Long.SIZE);
System.out.println(Long.BYTES);

Constant Meaning Value
MIN_VALUE Smallest possible long value -9223372036854775808
MAX_VALUE Largest possible long value 9223372036854775807
SIZE Number of bits used by long 64
BYTES Number of bytes used by long 8

Creating Long Objects

Modern Java code should avoid the deprecated Long constructors. Prefer autoboxing or Long.valueOf().


Long first = 5000L;
Long second = Long.valueOf(10000L);

System.out.println(first);
System.out.println(second);

The first statement uses autoboxing. The second explicitly obtains a Long object through valueOf().


Important: Prefer Long.valueOf() or autoboxing instead of creating wrapper objects with deprecated constructors.

Converting Long to long

The longValue() method extracts the primitive long from a Long object.


Long number = 9000000000L;

long value = number.longValue();

System.out.println(value);

In normal application code, explicit unboxing is often unnecessary because Java can perform it automatically.


Long number = 9000000000L;

long value = number;

Parsing a String into a Long

Real applications frequently receive numeric values as strings. For example, a large identifier may arrive from a text file, HTTP request, or configuration source. Long.parseLong() converts such text into a primitive long.


String text = "9876543210";

long number = Long.parseLong(text);

System.out.println(number);

If the supplied string does not contain a valid integer representation, the method throws NumberFormatException.


Long.valueOf() Versus Long.parseLong()

The two methods look similar, but they return different types.


Method Input Return Type
Long.parseLong() String long
Long.valueOf() String Long

long primitiveValue = Long.parseLong("9876543210");

Long wrapperValue = Long.valueOf("9876543210");

Use parseLong() when you need a primitive value for calculations. Use valueOf() when you need a Long object.


Comparing Long Values

The Long class provides methods for comparing values. When comparing wrapper objects, avoid using == as a general value-comparison technique.


Long first = 5000L;
Long second = 5000L;

System.out.println(first.equals(second));
System.out.println(Long.compare(first, second));

equals() compares the wrapped values, while Long.compare() compares two primitive long values after unboxing.


Common mistake: Do not depend on == for comparing two Long objects. Use equals() for value equality.

Useful Long Methods

Method Purpose
parseLong() Converts a String into a primitive long.
valueOf() Creates or obtains a Long representation of a value.
longValue() Returns the wrapped value as a long.
compare() Compares two long values.
compareTo() Compares one Long object with another.
toString() Converts a long value into its String representation.
max() Returns the greater of two long values.
min() Returns the smaller of two long values.
sum() Returns the sum of two long values.

Example: Long Operations

long a = 5000000000L;
long b = 7000000000L;

System.out.println(Long.max(a, b));
System.out.println(Long.min(a, b));
System.out.println(Long.sum(a, b));
System.out.println(Long.compare(a, b));

These methods provide convenient ways to perform common operations on long values without writing repetitive comparison logic.


Converting Long Values to Strings

The Long.toString() method converts a numeric value into its textual representation.


long accountNumber = 9876543210L;

String text = Long.toString(accountNumber);

System.out.println("Account: " + text);

This is useful when numeric information must be combined with text or passed to an API that expects a string.


Converting Long Values Between Number Bases

The Long class can convert a long value into binary, octal, and hexadecimal text representations.


long number = 255L;

System.out.println(Long.toBinaryString(number));
System.out.println(Long.toOctalString(number));
System.out.println(Long.toHexString(number));

These conversions are particularly useful when working with bit manipulation, low-level data, debugging, networking, and systems programming.


Parsing Different Number Bases

The overloaded parseLong() method can also interpret a string using a specified radix.


long binary = Long.parseLong("1010", 2);
long hexadecimal = Long.parseLong("FF", 16);

System.out.println(binary);
System.out.println(hexadecimal);

The second argument specifies the number base. In this example, 2 represents binary and 16 represents hexadecimal.


Long and Null Values

Because Long is a reference type, a variable of type Long can contain null.


Long timestamp = null;

System.out.println(timestamp);

However, unboxing a null Long causes a NullPointerException.


Long timestamp = null;

long value = timestamp;

Remember: A nullable Long can be useful when “no value” has meaning, but always check for null before unboxing.

Real-World Example: Database IDs

Large database identifiers are a common reason developers encounter Long. An application may need to represent IDs that can grow far beyond the range of a 32-bit integer.


Long customerId = 9876543210123L;

System.out.println("Customer ID: " + customerId);

The value remains comfortably within the range of a 64-bit long, making this type appropriate for many large identifier scenarios.


Best Practices

  • Use long when a primitive 64-bit integer is sufficient.
  • Use Long when an object or nullable value is required.
  • Remember the L suffix for large integer literals.
  • Use Long.parseLong() when you need a primitive long from text.
  • Use Long.valueOf() when an object representation is required.
  • Use equals() to compare Long objects by value.
  • Check for null before unboxing a Long reference.

Interview Insight

A common interview question is: “Why would you use Long instead of long?” A strong answer is that long is the primitive type used for efficient 64-bit integer calculations, while Long is the corresponding object type and is useful with Collections, Generics, object-based APIs, and nullable values.


Long Class at a Glance

Feature Key Point
Wrapper type Long wraps the primitive long.
Size 64 bits or 8 bytes.
Range -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Parsing parseLong() converts text to primitive long.
Object conversion valueOf() provides a Long object.
Comparison equals(), compare(), and compareTo() support comparisons.
Number bases Supports binary, octal, hexadecimal conversion, and radix-based parsing.
Null A Long reference can be null.

The Long class gives Java developers the object-oriented capabilities of a wrapper while preserving the large numeric range of the primitive long. Once you understand its parsing, conversion, comparison, and radix methods, working with large integer values becomes much more predictable and practical.

Post a Comment

0Comments
Post a Comment (0)