Java int Keyword
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 example below, 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 num_byte = 10; //Widening Casting short num_short = num_byte; int num_int = num_short; //printing variables System.out.println("num_byte = " + num_byte); System.out.println("num_short = " + num_short); System.out.println("num_int = " + num_int); } }
The output of the above code will be:
num_byte = 10 num_short = 10 num_int = 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 num_double = 10.5d; //Narrowing Casting float num_float = (float) num_double; long num_long = (long) num_float; int num_int = (int) num_long; //printing variables System.out.println("num_double = " + num_double); System.out.println("num_float = " + num_float); System.out.println("num_long = " + num_long); System.out.println("num_int = " + num_int); } }
The output of the above code will be:
num_double = 10.5 num_float = 10.5 num_long = 10 num_int = 10
❮ Java Keywords