Java Tutorial Java Advanced Java References

Java long Keyword



The Java long keyword is a primitive data types. The long data type is a 64-bit two's complement integer. Its default value is 0L and default size is 64 bits (8 byte). The range of a long value is -263 to 263-1.

Example: Create a long value

In the example below, variable x and y are created to store long values. Please note that, value with a "L" is used to represent the long value.

public class MyClass {
  public static void main(String[] args) {   
    //creating long values
    long x = 10l;
    long y = 10L;

    //printing variables
    System.out.println("x = " + x);
    System.out.println("y = " + y);    
  }
}

The output of the above code will be:

x = 10.5
y = 10.0

Example: Widening Casting (smaller to larger type)

A long value can be created by assigning a byte, a short or an int data to a long variable. The compiler implicitly typecast these data types to long as shown in the output.

public class MyClass {
  public static void main(String[] args) {       
    byte num_byte = 10;

    //Widening Casting
    short num_short = num_byte;
    int num_int = num_short;
    long num_long = num_int;

    //printing variables
    System.out.println("num_byte = " + num_byte); 
    System.out.println("num_short = " + num_short);
    System.out.println("num_int = " + num_int);
    System.out.println("num_long = " + num_long);
  }
}

The output of the above code will be:

num_byte = 10
num_short = 10
num_int = 10
num_long = 10

Example: Narrowing Casting (larger to smaller type)

For a larger data types like double and float, narrowing casting is required. The compiler explicitly typecast these data types to long as shown in the output.

public class MyClass {
  public static void main(String[] args) {    
    double num_double = 10.5d;

    //Narrowing Casting
    float num_float = (float) num_double;
    long num_long = (long) num_float;

    //printing variables
    System.out.println("num_double = " + num_double);
    System.out.println("num_float = " + num_float); 
    System.out.println("num_long = " + num_long);
  }
}

The output of the above code will be:

num_double = 10.5
num_float = 10.5
num_long = 10

❮ Java Keywords