The long keyword is a primitive data type in Java. Similar to int data type, it is used to store whole numbers. The range of long data type is much wider than int. A long data type has a range of -263(-9223372036854775808) to 263-1(9223372036854775807).
public class JavaExample { public static void main(String[] args) { long num = 12345678910L; System.out.println(num); } }
Output:
12345678910
Points to Note:
- The long values are ended with ‘L’ letter as shown in the above example.
- The size of long is 64 bit (8 bytes), which is higher than int so you should use int for the values that are within int data type range.
- The default value of long type variable is 0.
Example of long return type method
In this example, we have a method with long return type. Since we know, that the product of given numbers cannot be handled by an int data type so we have chosen long return type instead of int. As the result is out of range of int max value.
You should use long data type for such instances, where you expect that result would be out of range of an int.
public class JavaExample { public static long multiply(int a, int b){ return a*b; } public static void main(String[] args) { long product = multiply(10, 123456789); System.out.println(product); } }
Output:
1234567890