26

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).

reevesy
  • 3,452
  • 1
  • 26
  • 23
ReflectionHack
  • 365
  • 1
  • 3
  • 6

2 Answers2

39

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
6

All Java numeric types are signed. This was the designers decision. Some people think it was a bad idea to have signed byte. J.Bloch in an interview said "I'm going to say that the strangest thing about the Java platform is that the byte type is signed." http://www.theserverside.com/news/thread.tss?thread_id=51624

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 5
    `char` is unsigned. And byte should have been unsigned IMHO for the same reason. e.g. InputStream.read() reads an unsigned byte. – Peter Lawrey Jan 13 '14 at 11:01
  • 1
    Joshua Bloch would say it is strange, but in C/C++ most implementations have a signed 8-bit `char` – Nayuki Jul 30 '16 at 18:22