Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Short and Character apart from processing?

Tags:

java

For what I know:

  • "bytewise", it looks like they are the same (they are both 2 bytes long);
  • Character, however, has more processing to it (static .isLetter() method and others, etc).

While my questions may sound dumb, here they are:

  • unless my first assumption is wrong, why are there primitive types char and short since they have the same "internal length` and, anyway, there are no unsigned primitive types in Java?
  • Short is final, if it weren't, could Character have extended Short?

EDIT: answer given and I was wrong: there is one unsigned primitive type in Java and that is... char.

EDIT 2: @PatriciaShanahan also mentions that in arithmetic operations, a char behaves like an unsigned 16bit integer, just like a short. And this includes left shifts, that is, the sign bit is carried along, just like for short.

like image 260
fge Avatar asked Jan 07 '13 22:01

fge


1 Answers

The essential difference is that short is signed, char is unsigned.

public class CharVsShort {
  public static void main(String[] args) throws Exception {
    short ffShort = (short)0xFFFF;
    char ffChar = (char)0xFFFF;

    System.out.println("all-1s-short = " + (int)ffShort);
    System.out.println("all-1s-char  = " + (int)ffChar);
  }
}

prints

all-1s-short = -1
all-1s-char  = 65535

The Java Language Specification section 4.2 states that

The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units

(my bold). It also gives the types' ranges explicitly as

  • byte, from -128 to 127, inclusive
  • short, from -32768 to 32767, inclusive
  • int, from -2147483648 to 2147483647, inclusive
  • long, from -9223372036854775808 to 9223372036854775807, inclusive
  • char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
like image 172
Ian Roberts Avatar answered Oct 09 '22 18:10

Ian Roberts