The Java Long class is a wrapper class that provides an object representation of the primitive data type long. It allows you to perform various operations on long values by treating them as objects.
The Long class provides a set of methods that enable you to perform common operations on long values, such as converting strings to longs, performing arithmetic operations, comparing values, and more. Here are some basic use cases of the Long class:
- Converting between
longand String: The Long class provides theparseLong()method, which converts a String representation of a number into alongvalue. For example:
String numberString = "123456789"; long number = Long.parseLong(numberString);
- Converting
longto String: You can use thetoString()method of the Long class to convert alongvalue to its String representation. For example:
long number = 123456789; String numberString = Long.toString(number);
- Arithmetic operations: The Long class can performing arithmetic operations exactly like
, such as addition, subtraction, multiplication, and division. These arithmetic operations return Long objects. For example:long
long a = 10; long b = 5; Long sum = Long.valueOf(a) + Long.valueOf(b);
- Comparing values: The Long class provides methods to compare
longvalues. For example, you can use thecompareTo()method to compare two Long objects or theequals()method to check for equality. Here’s an example:
Long x = 100L; Long y = 50L; int result = x.compareTo(y);
- Long constants: The Long class defines constants like
MIN_VALUEandMAX_VALUE, which represent the minimum and maximum values that can be stored in alongvariable.
Long maxValue = Long.MAX_VALUE; // 9223372036854775807
Long minValue = Long.MIN_VALUE; // -9223372036854775808- Boxing and unboxing: The Long class allows you to convert between
longand Long objects through a process called boxing and unboxing. Boxing is the conversion of a primitivelongvalue to a Long object, and unboxing is the reverse process of extracting thelongvalue from a Long object.
Boxing:
long primitiveLong = 123456789L; Long boxedLong = primitiveLong; // Boxing: converting long to Long
Unboxing:
Long boxedLong = 987654321L; long primitiveLong = boxedLong; // Unboxing: extracting long from Long
It’s important to note that using the Long class incurs a small performance overhead compared to working directly with primitive long values. However, the Long class is useful in scenarios where you need to take advantage of its methods or when you require a long value to be treated as an object, such as when working with collections or using Java libraries that expect object-based representations.
Overall, the Long class provides a range of utility methods that make it easier to work with long values in various scenarios, offering additional functionality beyond what is available with the primitive long type alone.
