Junior — Middle
What are the differences between the primitive type short and its object representation Short in Java?
sobes.tech AI
Answer from AI
In Java, short is a primitive data type that occupies 2 bytes and stores a numeric value from -32768 to 32767.
Short is an object wrapper class for the primitive type short. Main differences:
- Primitive vs Object:
shortis primitive,Shortis an object. - Usage:
Shortis used when an object is needed, for example, in collections (List<Short>), where primitives cannot be used. - Autoboxing: Java automatically converts between
shortandShort(autoboxing and unboxing). - Methods:
Shortprovides methods, for example, for converting to string, comparison, etc., which primitives do not have.
Example:
short a = 10;
Short b = a; // autoboxing
short c = b; // unboxing
List<Short> list = new ArrayList<>();
list.add(a); // cannot add primitive directly, but autoboxing allows it
Thus, Short is needed for working with objects, and short for efficient storage of numbers.