Easy
Declare Short
Declare a short variable named age and assign it the value 21.
Show answer:
short age = 21; //21 is within the valid short range (–32,768 to 32,767)
Valid or invalid?
Which of the following values can be stored in a short?
- 120
- 40000
- -32768
- 32767
Show answer:
120 // Valid
40000 // Invalid. Outside short range (-32768 to 32767)
-32768 // Valid
32727 // Valid
Fix the error
short x = 100000;
Show answer:
100000 is too large for a short range (-32768 to 32767), so a larger integer type like int is required.
Primitive vs Wrapper
Which is a primitive and which is the wrapper class?
short a = 10;
Short b = 10;
Show answer:
short a = 10; // primitive
Short b = 10; // object (wrapper class)
Constants
Write a line of code that assigns the maximum possible short value to a variable named max.
Show answer:
Short.MAX_VALUE; // returns 32767
Medium
Convert String to short
Write code that converts the string "250" into a short value.
Show answer:
short value = Short.parseShort("250");
parseShort() converts a numeric String into a primitive short.
Trouble shooting
What happens if this code runs? Name the exception thrown.
Short.parseShort("hello");
Show answer:
A NumberFormatException is thrown. "hello" is not numeric, so Java cannot convert it to a short.
Primitive Method Error
Why does this code cause a compile-time error?
short x = 3;
x.compareTo((short) 4);
Show answer:
Primitive types do not have methods.
Hard
Overflow
What value is stored in x after this code runs?
Show answer:
short x = 32767;
x++;
Result: x becomes -32768. This is overflow. When a short exceeds its maximum value, it wraps around to the minimum value.
Mixing Types
Why does this code not compile? How can you fix it?
Show answer:
The expression a + b is automatically promoted to an int.
Fix
short c = (short) (a + b);
(short) is an explicit cast that forces Java to convert an int result into a short.
Autoboxing
What is autoboxing, and how does it apply to this line of code?
Short s = 10;
Show answer:
Autoboxing is Java automatically converting a primitive into its wrapper object.
Short s = 10; // Java automatically converts the primitive 10 into a Short object.
Leave a Reply