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.
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.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.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
myShortof typeshortand assign it the value 10000. - We then declare
maxShortandminShortand assign them the maximum and minimum values that ashortcan hold. - We use
System.out.println()to print the values of these variables to the console.
- We declare a variable
Save the file (Ctrl+S or Cmd+S).
Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. If not, use the commandcd ~/project. Then, compile the code using thejavaccommand:javac HelloJava.javaIf there are no errors, the compilation is successful, and a
HelloJava.classfile will be created in the~/projectdirectory.Finally, run the compiled program using the
javacommand:java HelloJavaYou 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.
Open the
HelloJava.javafile in the WebIDE editor.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
intvariablelargeIntwith the value 40000, which is greater than the maximum value ashortcan 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 theintvalue to ashort. The(short)beforelargeIntis the cast operator. - We do the same for a negative value
anotherLargeInt(-40000), which is less than the minimum value ashortcan hold (-32768).
- We declare an
Save the file (Ctrl+S or Cmd+S).
Now, compile the modified program in the Terminal:
javac HelloJava.javaThis time, the compilation should be successful because we used type casting.
Run the compiled program:
java HelloJavaYou 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.
Open the
HelloJava.javafile in the WebIDE editor.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
shortvalue (maxShort). - We add 1 to
maxShort. By default, arithmetic operations involvingshort(andbyte) are promoted toint. So,maxShort + 1results in anint. We store this inoverflowInt. - We then cast
overflowIntback to ashortand store it inoverflowShort. This is where the overflow happens, and the value wraps around. - We do similar operations with the minimum
shortvalue (minShort), subtracting 1 to demonstrate underflow.
- We start with the maximum
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaYou 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.



