Table of Contents
What is the difference between signed and unsigned variables?
Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges.
Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive.
Unsigned and signed variables of the same type (such as int and byte) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable.
For example, an unsigned byte can represent values from 0 to 255, while signed byte can represent -128 to 127. (Adding 128 + 127 = 255)[1]
To reiterate, the main differences between Signed & Unsigned data type or variable in java is:
- Unsigned can hold larger positive values, but no negative values.
- Unsigned uses the leading bit as a part of the value, while the signed version uses the leftmost bit to identify whether the number is positive or negative. Alternatively, two’s complement can be used to designate a number as positive or negative.
- Re-iterating, Signed data types can hold positive and negative numbers
Why Does Java have Signed and Unsigned Data Types?
Java only supports signed types (except char) because it was assumed that one type was simpler for beginners to understand than having two types for each size. In C it was perceived to be a source of error so support for unsigned types was not included.
So the designers picked four sizes:
- byte, 8 bit
- short, 16 bit
- int, 32 bit
- long, 64 bit.
And to keep things consistent they were all signed just like float and double However a signed byte is rarely very useful and given they allowed unsigned 16-bit char having an unsigned byte might have made more sense.
Where this doesn’t work so well is when you have to interact with systems which use unsigned integer types. This can be source of confusion and to which type to use instead because often it doesn’t make any difference. Java 8 will have operations to support unsigned types as well. These are added to the wrapper classes like Integer and Long.[2]
Links
Sources
- What is the difference between signed and unsigned variables? [Stack Overflow]
- Signed and unsigned data types in java [Stack Overflow]