long Keyword in Java
The long keyword in Java is a primitive data type used to store large integer values. If your program needs to handle numbers beyond the range of int, then long is the ideal choice.
It occupies 64 bits (8 bytes) in memory and can store values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Syntax
long variableName = value;
When Should You Use long?
- When working with very large numbers, such as financial calculations, file sizes, or time in milliseconds.
- When the value exceeds the maximum range of
int(231-1).
Example 1: Declaring and Printing a long Variable
public class LongExample1 {
public static void main(String[] args) {
long population = 7800000000L;
System.out.println("World Population: " + population);
}
}
World Population: 7800000000
Explanation: Notice the L at the end of the number. By default, Java treats whole numbers as int. Appending L tells Java this number should be interpreted as a long.
Example 2: What Happens Without L?
public class LongExample2 {
public static void main(String[] args) {
long bigValue = 2200000000; // Compilation error
System.out.println(bigValue);
}
}
error: integer number too large: 2200000000
Explanation: Java assumes numeric literals are int by default. Without the L, the number is too large to be stored in an int, causing a compilation error.
Example 3: Arithmetic with long
public class LongExample3 {
public static void main(String[] args) {
long millisecondsPerDay = 24L * 60 * 60 * 1000;
System.out.println("Milliseconds in a Day: " + millisecondsPerDay);
}
}
Milliseconds in a Day: 86400000
Explanation: Using L ensures that at least one operand is a long, so the result is also a long. This avoids overflow when dealing with large products.
Default Value of long
If a long variable is declared as a class-level field and not initialized, Java assigns it a default value of 0L.
public class LongExample4 {
static long count;
public static void main(String[] args) {
System.out.println("Default value: " + count);
}
}
Default value: 0
Comparison with Other Integer Types
| Type | Size (bits) | Min Value | Max Value |
|---|---|---|---|
byte | 8 | -128 | 127 |
short | 16 | -32,768 | 32,767 |
int | 32 | -231 | 231-1 |
long | 64 | -263 | 263-1 |
Key Points to Remember
longis used for storing large integers beyond the capacity ofint.- Always use
Lorlsuffix to denote alongliteral. Prefer uppercaseLfor readability. - Default value of an uninitialized class-level
longis0L. - Mixing
intandlongin expressions may lead to implicit type conversions.
Comments
Loading comments...