Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signed and unsigned data types in java

Tags:

I have a bit of confusion regarding which unsigned data types does Java support?

I have read Why doesn't Java support unsigned ints? but I don't understand its very complicated explanation (to me at least).

like image 582
ReflectionHack Avatar asked Jan 13 '14 10:01

ReflectionHack


People also ask

What are signed and unsigned data types?

The XDR standard defines signed integers as integer. A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].

Is Java signed or unsigned?

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.

What is unsigned data type?

An unsigned data type simply means that the data type will only hold positive values; negatives aren't allowed to be stored in the data type. Unsigned data types include int, char, short, and long.

Does Java have unsigned types?

Java does have unsigned types, or at least one: char is an unsigned short.


1 Answers

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

like image 85
Peter Lawrey Avatar answered Sep 25 '22 13:09

Peter Lawrey