short
About
Definition:
short
is 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,768
to32,767
(-2^15
to2^15 - 1
).Default Value: The default value of
short
is0
.Wrapper Class: The wrapper class for
short
isShort
, located injava.lang
.
Characteristics
Signed Integer Representation: The
short
type 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,
short
supports arithmetic operations such as addition, subtraction, multiplication, and division.Promotion in Expressions: In arithmetic expressions,
short
values are automatically promoted toint
before any operation. Example:Usage in Streams: Since Java Streams operate on
int
,short
values 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
short
Arithmetic 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
short
can cause data loss due to overflow.Automatic Promotion: Arithmetic operations promote
short
toint
, which can lead to unexpected results.
Examples
Basic example
Using short
in Arrays
short
in ArraysConverting short
to String
short
to String
Using short
with Streams
short
with StreamsShort as Bit Fields
Handling Large Short Arrays
Wrapper Class Example
Last updated
Was this helpful?