Java

What is long Keyword in Java

A Java basic data type is the long keyword. It is used to hold whole numbers and is comparable to the int data type. Long data types have a substantially larger range than ints. The range of a long data type is -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 letter “L” is used to signify the end of long values, as in the example above.
  • Use int for values that fall within the range of the int data type since long’s size is bigger at 64 bit (8 bytes), which is higher than int.
  • The long type variable’s default value is 0.

Example of long return type method

We have a method with a long return type in this example. We picked the long return type instead of the int data type because we are aware that the product of the provided values cannot be handled by an int data type. Because of the outcome, the int max value is not valid.

When you anticipate that the outcome will be outside of an int’s range, you should utilize the long data type.

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

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button