⬅ Previous Topic
Java interface KeywordNext Topic ⮕
Java native Keyword⬅ Previous Topic
Java interface KeywordNext Topic ⮕
Java native Keywordlong
Keyword in JavaThe 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
.
long variableName = value;
long
?int
(231-1).long
Variablepublic 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
.
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.
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.
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
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 |
long
is used for storing large integers beyond the capacity of int
.L
or l
suffix to denote a long
literal. Prefer uppercase L
for readability.long
is 0L
.int
and long
in expressions may lead to implicit type conversions.⬅ Previous Topic
Java interface KeywordNext Topic ⮕
Java native KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.