Java Long Shortvalue Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn about the shortValue() method of Long class in Java, which is used to convert a Long object into a short value. We will discuss the usage, syntax, parameters, and returns of this method. We will also go through some examples to understand how this method works.

Create a Long Object

Create a Long object with a value of your choice. This object would be used to convert into a short value using the shortValue() method.

// creating a Long object
Long myLong = 123456789L;

Convert Long Object to short Value

Invoke the shortValue() method on the Long object created in Step 1 to get the short equivalent.

// converting Long object to short value
short myShort = myLong.shortValue();

Print the short Value

Print the short value obtained in Step 2 to the console.

// printing short value
System.out.println("Short value: " + myShort);

Check for Overflow

If the Long value is too large to be converted into a short, make sure to check for possible overflow. In case of overflow, DataFormatException will be thrown.

// checking for overflow
if (myLong > Short.MAX_VALUE || myLong < Short.MIN_VALUE) {
    throw new DataFormatException("Value out of range for conversion to short");
}

Handle Exceptions

In case of an exception, handle it gracefully and print an appropriate error message.

try {
    // perform all steps here
} catch (DataFormatException ex) {
    System.out.println(ex.getMessage());
}

Compile and Run the Code

Compile the code using the javac command and run the code using the java command in the terminal.

$ javac LongShortValue.java
$ java LongShortValue

You should see the output of the code on the console.

Optional): User Input

Instead of hardcoding the Long value, you can also take user input from the console and perform the conversion.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Long value: ");
long myLongValue = scanner.nextLong();
Long myLongObject = myLongValue;
short myShort = myLongObject.shortValue();
System.out.println("Short value: " + myShort);

Summary

In this lab, we learned about the shortValue() method of the Long class in Java, which is used to convert a Long object into a short value. We learned about the syntax, parameters, and returns of this method. We also went through multiple examples to understand how to use this method in different scenarios.