Java - Data Types short type

What is short type?

Java short data type is a 16-bit signed primitive integer data type.

The range of short type is -32768 to 32767 (or -2^15 to 2^15 - 1).

There is no short literal. You can assign int literal within the range of short (-32768 to 32767) to a short variable.

For example,

short s1 = 11111;   // ok 
short s2 = -11111;  // ok 
  

The value of a byte variable can be assigned to a short variable since the range of the byte data type falls within the range of the short data type.

short s1 = 15;  // ok 
byte b1 = 110;   // ok 
s1 = b1;        // ok 

The following snippet of code illustrates the assignment of byte, int, and long values to short variables:

int num1 = 10;    // ok 
//s1 = num1;        // A compile-time error 
short s1 = (short)num1; // ok because of cast from int to short 
//s1 = 135000;       // A compile-time error of an int literal outside the short range 
  
long num2 = 555L; // ok 
//s1 = num2;        // A compile-time error 
s1 = (short)num2; // ok because of the cast from long to short 
//s1 = 555L;        // A compile-time error 
s1 = (short)555L;  // ok because of the cast from long to short 

Demo

public class Main {
  public static void main(String[] args) {
    int num1 = 10; // ok
    // s1 = num1; // A compile-time error
    short s1 = (short) num1; // ok because of cast from int to short
    // s1 = 135000; // A compile-time error of an int literal outside the short
    // range/*from w w  w. jav a  2  s.c  o m*/
    System.out.println(s1);
    
    long num2 = 555L; // ok
    // s1 = num2; // A compile-time error
    s1 = (short) num2; // ok because of the cast from long to short
    System.out.println(s1);
    
    // s1 = 555L; // A compile-time error
    s1 = (short) 555L; // ok because of the cast from long to short
    System.out.println(s1);

  }
}

Result

Short class

Java has a class called Short.

Short class defines two constants to represent maximum and minimum values of short data type, Short.MAX_VALUE and Short.MIN_VALUE.

Demo

public class Main {
  public static void main(String[] args) {
    short max = Short.MAX_VALUE; 
    short min = Short.MIN_VALUE; 

    System.out.println(max);//  w w  w .jav  a 2 s. c o  m
    System.out.println(min);
  }
}

Result