Introduction
The Short
class in Java is a wrapper for the primitive type short
. It provides methods to manipulate short values and handle conversions between different numeric types.
Table of Contents
- What is the
Short
Class? - Common Methods
- Examples of Using the
Short
Class - Conclusion
1. What is the Short Class?
The Short
class wraps a value of the primitive type short
in an object. It provides methods for converting and comparing short values.
2. Common Methods
Short.valueOf(short s)
: Returns aShort
instance representing the specifiedshort
value.Short.parseShort(String s)
: Parses the string argument as a signed decimalshort
.shortValue()
: Returns the value of thisShort
as ashort
.intValue()
: Returns the value of thisShort
as anint
.doubleValue()
: Returns the value of thisShort
as adouble
.compareTo(Short anotherShort)
: Compares twoShort
objects.equals(Object obj)
: Compares this object to the specified object.
3. Examples of Using the Short Class
Example 1: Creating and Comparing Short
Values
This example demonstrates how to create and compare Short
values.
public class ShortExample { public static void main(String[] args) { Short s1 = Short.valueOf((short) 10); Short s2 = Short.valueOf((short) 20); System.out.println("s1: " + s1); System.out.println("s2: " + s2); System.out.println("s1 equals s2: " + s1.equals(s2)); System.out.println("s1 compareTo s2: " + s1.compareTo(s2)); } }
Output:
s1: 10 s2: 20 s1 equals s2: false s1 compareTo s2: -10
Example 2: Parsing a String
to Short
This example shows how to parse a String
into a Short
.
public class ParseShortExample { public static void main(String[] args) { String number = "100"; short parsedValue = Short.parseShort(number); System.out.println("Parsed short value: " + parsedValue); } }
Output:
Parsed short value: 100
Example 3: Converting Short
to Other Types
This example demonstrates converting a Short
to other numeric types.
public class ShortConversionExample { public static void main(String[] args) { Short s = Short.valueOf((short) 25); int intValue = s.intValue(); double doubleValue = s.doubleValue(); System.out.println("Short value: " + s); System.out.println("Converted to int: " + intValue); System.out.println("Converted to double: " + doubleValue); } }
Output:
Short value: 25 Converted to int: 25 Converted to double: 25.0
4. Conclusion
The Short
class in Java provides a convenient way to handle and manipulate short values. It offers methods for conversion, comparison, and parsing, making it useful for operations involving short integers.