The short Data Type - Java Language Basics

Java examples for Language Basics:short

Introduction

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

Its range is -32768 to 32767 (or -2^15 to 2^15 - 1).

short s1 = 129;   // ok 
short s2 = -1189;  // ok 
  

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

short s1 = 15;  // ok 
byte b1 = 10;   // ok 
s1 = b1;        // ok 
  
int num1 = 10;    // ok 
s1 = num1;        // A compile-time error 
s1 = (short)num1; // ok because of cast from int to short 
s1 = 35555;       // A compile-time error of an int literal outside the short range 
  
long num2 = 5555L; // 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 
s = (short)5555L;  // ok because of the cast from long to short 
  

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

short max = Short.MAX_VALUE; 
short min = Short.MIN_VALUE;

Related Tutorials