What Is Short Data Type in Java With Example?
In Java, the short data type is used to store numeric values that range from -32,768 to 32,767. It is a 16-bit signed two’s complement integer.
The short data type is useful when memory space is a concern and you know that the value you want to store will fall within its limited range.
Declaration and Initialization of a short Variable
To declare a short variable in Java, you can use the following syntax:
short myVariable;
To initialize the variable with a specific value, you can assign it during declaration or at a later stage using the assignment operator (=). Here’s an example:
short myAge = 25;
You can also declare multiple short variables on the same line by separating them with commas. For example:
short x = 10, y = 20, z = 30;
Using the short Data Type in Java Programs
Now that we know how to declare and initialize a short variable let’s see some examples of how it can be used in Java programs.
Example 1: Addition of Two short Variables
short num1 = 100; short num2 = 200; short sum = (short) (num1 + num2); System.out.println("Sum: " + sum);
In this example, we declare three short variables: num1, num2, and sum. We then calculate the sum of num1 and num2 and store the result in the sum variable.
Since the addition of two short variables can exceed their range, we need to explicitly cast the result back to a short using (short). Finally, we print the value of sum.
Example 2: Comparison of Two short Variables
short num1 = 100; short num2 = 200; if (num1 > num2) { System.println("num1 is greater than num2"); } else if (num1 < num2) { System.println("num1 is less than num2"); } else { System.println("num1 is equal to num2"); }
In this example, we compare two short variables, num1 and num2. Depending on their values, we print the appropriate message.
The comparison operators (>, <, and =) work as expected with short variables.
Conclusion
The short data type in Java allows you to store integer values within a limited range. It is particularly useful when memory space is a concern and you know that your values will fall within its range.
Remember to be cautious when performing operations on short variables that may exceed their limits.
I hope this article has provided you with a clear understanding of the short data type in Java along with some examples demonstrating its usage.