S.Klumpers S.Klumpers - 11 months ago 27
Java Question

Java doesn't box and convert primitive types at the same time

I know that java(c?) can box and unbox types and convert between primitive types when necessary, but why does it not want to do that both at the same time.

For example if I were to do this:

ArrayList<Byte> bytes = new ArrayList<>();

Javac will panic and tell me
is not applicable, but were I to use
instead it would not be a problem.
If I would do
byte aByte = 8; bytes.add(aByte);
it would also compile fine.

Why is this, is there a good reason for this?


The reason why this happen is because if you do bytes.add(8), 8 is handled as an int. So the following error is thrown:

The method add(Byte) in the type ArrayList < Byte> is not applicable for the arguments (int)

If you want to add 8 directly to your ArrayList you have to cast 8 to a byte


It is not possible to handle 8 as a byte when necessary and in other cases as an int.

Think of the following example:

private static void test() {
  Object o = 8;

Now there wouldn't be specified if you want 8 as an byte or an int. So numbers are handled always as ints and no as bytes. So the JVM can box the 8 to the correct wrapper class. o.getClass() is java.lang.Integer in this example.

The same thing is with decimals,e.g. 2.3 is defined as a double if you want 2.3 as an float you have to write 2.3f.