The long data type is a 64-bit signed Java primitive data type.
It is used when the result of calculations on whole numbers may exceed the range of the int data type.
Its range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (-263 to 263 - 1).
All whole numbers in the range of long are called integer literals of long type. An integer literal of type long always ends with L or lowercase l.
The following are examples of using a integer literal of long type:
long num1 = 0L; long num2 = 4L; long mum3 = -3; long num4 = 8; long num5 = -1L;
Integer literals of long type can be expressed in octal, hexadecimal, and binary formats. For example,
long num1; num1 = 25L; // Decimal format num1 = 031L; // Octal format num1 = 0X19L; // Hexadecimal format num1 = 0b11001L; // Binary format
When a long literal is assigned to a variable of type long, the Java compiler checks the value being assigned and makes sure that it is in the range of the long data type; otherwise it generates a compile time error.
The assignment from int to long is valid, because all values that can be stored in an int variable can be stored in a long variable. However, the reverse is not true.
You cannot simply assign the value stored in a long variable to an int variable.
There is a possibility of value overflow.
To assign the value of a long variable to an int variable, use "cast" in Java, like so:
num1 = (int)num2;
Java has a class Long, which defines two constants to represent maximum and minimum values of long data type, Long.MAX_VALUE and Long.MIN_VALUE.
long max = Long.MAX_VALUE; long min = Long.MIN_VALUE;