Java short Keyword
The Java short keyword is a primitive data types. The short data type is a 16-bit signed two's complement integer. Its default value is 0 and default size is 16 bits (2 byte). The range of a short value is -32,768 to 32,767 (inclusive).
Example: Create a short value
In the example below, variable x and y are created to store short values.
public class MyClass { public static void main(String[] args) { //creating short values short x = 10; short 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)
A short value can be created by assigning a byte data to a short variable. The compiler implicitly typecast this data type to short 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; //printing variables System.out.println("num_byte = " + num_byte); System.out.println("num_short = " + num_short); } }
The output of the above code will be:
num_byte = 10 num_short = 10
Example: Narrowing Casting (larger to smaller type)
For a larger data types like double, float, long, and int, narrowing casting is required. The compiler explicitly typecast these data types to short 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; short num_short = (short) num_int; //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); System.out.println("num_short = " + num_short); } }
The output of the above code will be:
num_double = 10.5 num_float = 10.5 num_long = 10 num_int = 10 num_short = 10
❮ Java Keywords