short
About
Definition:
shortis one of the eight primitive data types in Java used to store integer values with a smaller range compared toint. It is particularly useful when memory usage is a concern and the values fit within its range.Size: Occupies 2 bytes (16 bits) in memory.
Value Range:
-32,768to32,767(-2^15to2^15 - 1).Default Value: The default value of
shortis0.Wrapper Class: The wrapper class for
shortisShort, located injava.lang.
Characteristics
Signed Integer Representation: The
shorttype is signed, meaning it can represent both positive and negative integers.Compact Data Type: Compared to
int, it saves memory, especially useful for large arrays of small numbers.Arithmetic Operations: Like other numeric types,
shortsupports arithmetic operations such as addition, subtraction, multiplication, and division.Promotion in Expressions: In arithmetic expressions,
shortvalues are automatically promoted tointbefore any operation. Example:short a = 10; short b = 20; int result = a + b; // Promoted to intUsage in Streams: Since Java Streams operate on
int,shortvalues must be converted or boxed to work with streams.Interoperability: Often used in file handling, network protocols, and legacy systems where compact data representation is required.
Memory Usage: Requires 16 bits (2 bytes) per value, stored in signed 2’s complement representation.
Operations with short
shortArithmetic and Logical Operations
Operation
Example
Description
Arithmetic Operations
short a = 10 + 20;
Addition, subtraction, multiplication, division.
Comparison Operations
a > b
Compares two short values.
Casting
(short) largeValue
Explicitly cast larger types like int to short.
Conversion Methods
Conversion
Method
Example
short to String
String.valueOf(short)
String.valueOf(100) → "100"
String to short
Short.parseShort(String)
Short.parseShort("123") → 123
short to int
Implicit conversion
int value = shortVar;
int to short
Explicit cast (short)
(short) 50000 → Overflow behavior
short to double
Implicit conversion
double value = shortVar;
Short Wrapper Class (Short)
Short)Method
Description
Short.valueOf(short s)
Returns a Short instance for the given short value.
Short.parseShort(String s)
Parses the string argument as a short.
Short.toString(short s)
Converts short to its String representation.
Short.compare(short x, y)
Compares two short values.
Short.MIN_VALUE
Minimum value of short (-32,768).
Short.MAX_VALUE
Maximum value of short (32,767).
Common Mistakes
Overflow Issues: Casting a larger integer to
shortcan cause data loss due to overflow.Automatic Promotion: Arithmetic operations promote
shorttoint, which can lead to unexpected results.
Examples
Basic example
Using short in Arrays
short in ArraysConverting short to String
short to StringUsing short with Streams
short with StreamsShort as Bit Fields
Handling Large Short Arrays
Wrapper Class Example
Last updated