Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


The Java int keyword is a primitive data types. The int data type is a 32-bit signed two's complement integer. Its default value is 0 and default size is 32 bits (4 byte). The range of a int value is -231 to 231-1.

Example: Create a int value

In the below example, variable x and y are created to store int values.

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

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

The output of the above code will be:

x = 10
y = 20

Example: Widening Casting (smaller to larger type)

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

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

    //Widening Casting
    short j = i;
    int k = j;

    //printing variables
    System.out.println("i = " + i); 
    System.out.println("j = " + j);
    System.out.println("k = " + k);
  }
}

The output of the above code will be:

i = 10
j = 10
k = 10

Example: Narrowing Casting (larger to smaller type)

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

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

    //Narrowing Casting
    float j = (float) i;
    long k = (long) j;
    int l = (int) k;

    //printing variables
    System.out.println("i = " + i);
    System.out.println("j = " + j); 
    System.out.println("k = " + k);
    System.out.println("l = " + l);  
  }
}

The output of the above code will be:

i = 10.5
j = 10.5
k = 10
l = 10

❮ Java Keywords