Convert String To Short in Java

1. Introduction

Converting a string to a short data type is a specific task in Java when handling small integer values. The Short.parseShort() method is typically used for obtaining a primitive short value, and Short.valueOf() is used when you need an object of type Short. This tutorial will demonstrate both methods.

Key Points

- Short.parseShort(String s) converts a string to a primitive short.

- Short.valueOf(String s) converts a string to a Short object.

- Both methods throw NumberFormatException if the string does not contain a parsable short.

2. Program Steps

1. Define a string that represents a short value.

2. Convert the string to a primitive short using Short.parseShort().

3. Convert the string to a Short object using Short.valueOf().

4. Print both converted values.

3. Code Program

public class StringToShortExample {
    public static void main(String[] args) {
        // String to be converted
        String shortString = "32767";

        // Convert string to primitive short
        short shortPrimitive = Short.parseShort(shortString);

        // Convert string to Short object
        Short shortObject = Short.valueOf(shortString);

        // Print the results
        System.out.println("Converted to primitive short: " + shortPrimitive);
        System.out.println("Converted to Short object: " + shortObject);
    }
}

Output:

Converted to primitive short: 32767
Converted to Short object: 32767

Explanation:

1. String shortString = "32767": Initializes a string that represents the maximum value a short can hold.

2. short shortPrimitive = Short.parseShort(shortString): Converts the string to a primitive short. Useful when dealing with numeric data that requires less space and is within the short range.

3. Short shortObject = Short.valueOf(shortString): Converts the string to a Short object, useful for object-oriented operations where objects are needed instead of primitives.

4. System.out.println("Converted to primitive short: " + shortPrimitive) and System.out.println("Converted to Short object: " + shortObject): Outputs both the primitive and object type conversions to the console, verifying their success.


Comments