How to Check If an Integer Is Within Short Range in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an integer value falls within the range of the short data type in Java. We will begin by understanding the defined range of short (-32768 to 32767) and then proceed to verify integer values against these limits. Finally, we will explore how to handle boundary values effectively.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/type_casting("Type Casting") subgraph Lab Skills java/data_types -.-> lab-560007{{"How to Check If an Integer Is Within Short Range in Java"}} java/type_casting -.-> lab-560007{{"How to Check If an Integer Is Within Short Range in Java"}} end

Set Short Range (-32768 to 32767)

In this step, we will explore the short data type in Java and understand its range. In programming, data types are used to classify different types of data that a variable can hold. The short data type is a 16-bit signed two's complement integer. This means it can store whole numbers, both positive and negative, within a specific range.

The range of a short in Java is from -32,768 to 32,767. Understanding these limits is crucial to avoid errors like overflow or underflow, which happen when you try to store a value outside the data type's range.

Let's create a simple Java program to see the short data type in action and observe its limits.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            // Declare and initialize a short variable
            short myShort = 10000;
            System.out.println("My short variable: " + myShort);
    
            // Demonstrate the maximum value of short
            short maxShort = 32767;
            System.out.println("Maximum short value: " + maxShort);
    
            // Demonstrate the minimum value of short
            short minShort = -32768;
            System.out.println("Minimum short value: " + minShort);
        }
    }

    In this code:

    • We declare a variable myShort of type short and assign it the value 10000.
    • We then declare maxShort and minShort and assign them the maximum and minimum values that a short can hold.
    • We use System.out.println() to print the values of these variables to the console.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. If not, use the command cd ~/project. Then, compile the code using the javac command:

    javac HelloJava.java

    If there are no errors, the compilation is successful, and a HelloJava.class file will be created in the ~/project directory.

  5. Finally, run the compiled program using the java command:

    java HelloJava

    You should see the following output in the Terminal:

    My short variable: 10000
    Maximum short value: 32767
    Minimum short value: -32768

This output confirms that our short variables are holding the expected values within the defined range. In the next step, we will explore what happens when we try to assign values outside this range.

Verify Integer Against Short Limits

In the previous step, we saw how to declare and use short variables within their valid range. Now, let's explore what happens when we try to assign a value that is outside the short range to a short variable.

Java has different integer data types, including byte, short, int, and long, each with a different range. An int (integer) is a 32-bit signed two's complement integer, with a range from -2,147,483,648 to 2,147,483,647. This range is much larger than that of a short.

When you try to assign a value from a larger data type (like int) to a smaller data type (like short), Java requires you to explicitly tell it that you are aware of the potential loss of information. This is called type casting. If you don't cast, Java will give you a compilation error to prevent accidental data loss.

Let's modify our HelloJava.java program to demonstrate this.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            int largeInt = 40000; // This value is outside the short range
    
            // Attempt to assign largeInt to a short variable without casting
            // short myShort = largeInt; // This line will cause a compilation error
    
            // To assign a value from a larger type, we need to cast it
            short myShort = (short) largeInt;
            System.out.println("Value of largeInt cast to short: " + myShort);
    
            int anotherLargeInt = -40000; // Another value outside the short range
            short anotherShort = (short) anotherLargeInt;
            System.out.println("Value of anotherLargeInt cast to short: " + anotherShort);
        }
    }

    In this updated code:

    • We declare an int variable largeInt with the value 40000, which is greater than the maximum value a short can hold (32767).
    • The commented-out line short myShort = largeInt; shows what would happen without casting โ€“ a compilation error.
    • The line short myShort = (short) largeInt; demonstrates how to cast the int value to a short. The (short) before largeInt is the cast operator.
    • We do the same for a negative value anotherLargeInt (-40000), which is less than the minimum value a short can hold (-32768).
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, compile the modified program in the Terminal:

    javac HelloJava.java

    This time, the compilation should be successful because we used type casting.

  5. Run the compiled program:

    java HelloJava

    You will see output similar to this:

    Value of largeInt cast to short: -25536
    Value of anotherLargeInt cast to short: 25536

Notice that the output values (-25536 and 25536) are not the original values (40000 and -40000). This is because when you cast a value that is outside the range of the target data type, the value "wraps around". This is an example of overflow (for positive values exceeding the max) and underflow (for negative values exceeding the min). The exact resulting value depends on how the numbers are represented in binary. This demonstrates why understanding data type ranges and using casting carefully is important to avoid unexpected results.

Handle Boundary Values

In the previous steps, we learned about the short data type's range and saw what happens when we cast larger integer values that are outside this range. It's also important to understand how Java handles values exactly at the boundaries of the short range (-32768 and 32767).

When you work with values at the boundaries, you need to be careful, especially when performing arithmetic operations. Adding 1 to the maximum value or subtracting 1 from the minimum value can lead to overflow or underflow, causing the value to wrap around to the other end of the range.

Let's modify our HelloJava.java program one last time to demonstrate this boundary behavior.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Replace the existing code with the following:

    public class HelloJava {
        public static void main(String[] args) {
            short maxShort = 32767;
            System.out.println("Maximum short value: " + maxShort);
    
            // Adding 1 to the maximum short value
            // Note: The result of maxShort + 1 is an int by default
            int overflowInt = maxShort + 1;
            System.out.println("Maximum short + 1 (as int): " + overflowInt);
    
            // Casting the overflowed int back to short
            short overflowShort = (short) overflowInt;
            System.out.println("Maximum short + 1 (cast to short): " + overflowShort);
    
            short minShort = -32768;
            System.out.println("Minimum short value: " + minShort);
    
            // Subtracting 1 from the minimum short value
            // Note: The result of minShort - 1 is an int by default
            int underflowInt = minShort - 1;
            System.out.println("Minimum short - 1 (as int): " + underflowInt);
    
            // Casting the underflowed int back to short
            short underflowShort = (short) underflowInt;
            System.out.println("Minimum short - 1 (cast to short): " + underflowShort);
        }
    }

    In this code:

    • We start with the maximum short value (maxShort).
    • We add 1 to maxShort. By default, arithmetic operations involving short (and byte) are promoted to int. So, maxShort + 1 results in an int. We store this in overflowInt.
    • We then cast overflowInt back to a short and store it in overflowShort. This is where the overflow happens, and the value wraps around.
    • We do similar operations with the minimum short value (minShort), subtracting 1 to demonstrate underflow.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see output similar to this:

    Maximum short value: 32767
    Maximum short + 1 (as int): 32768
    Maximum short + 1 (cast to short): -32768
    Minimum short value: -32768
    Minimum short - 1 (as int): -32769
    Minimum short - 1 (cast to short): 32767

As you can see, when we add 1 to the maximum short value (32767) and cast it back to short, it wraps around to the minimum value (-32768). Similarly, subtracting 1 from the minimum short value (-32768) and casting back to short wraps around to the maximum value (32767).

This behavior is important to remember when working with fixed-size integer types like short. Always be mindful of the data type's range to prevent unexpected results due to overflow or underflow.

Summary

In this lab, we learned about the short data type in Java, understanding its 16-bit signed two's complement nature and its specific range from -32,768 to 32,767. We explored how to declare and initialize short variables and demonstrated the maximum and minimum values it can hold through a simple Java program. This foundational step is crucial for avoiding potential overflow or underflow errors when working with integer values within this range.