0

I'm a beginner to Java, I'm fooling around with primitive numerical types, and when I parse String to Byte I can't work with the resulting byte variable (I'm squaring it), as error returned "is type mismatch: cannot convert from int to byte."

static byte squareByte(String p1){


       //parse String to byte

        byte result = Byte.parseByte(p1);


       //return type byte

       return result * result;
}

I've used "System.out.println( ((Object)result).getClass().getName());" to determine the variable type after parsing to byte, and it prints that it is byte, so why do I get an error regarding the result being an int?

I find I have to parseByte and then cast Byte just for the multiplication to work, can somebody explain why I have this problem with both Byte and Short, but not with any other primitive numerical type?

  • what do you think will will happen when `p1 == 256`? –  Nov 17 '14 at 12:40
  • As an additional comment on the answers: the JVM (Java Virtual Machine) uses `int` sized instructions for smaller types (short, byte); comparable to common hardware CPUs. Hence there is no overhead in `byte*byte` yielding a byte more. – Joop Eggen Nov 17 '14 at 12:46

3 Answers3

1

By default, the * operator returns int. If you want another type, like byte, you will have to do a cast, but there's a risk might overflow the type.

return (byte) (result * result);

Think of what will happen if the multiplication exceeds the value of 127, which is the byte limit?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

This happens because the JLS specifies that math operations like multiplication / addition etc must return an int You have to use - return (byte) (result * result); to explicitly convert the integer result to byte.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

When you perform any arithmetic operations (namely +,-,*,/ or %) with primitive types that are smaller than int, then the values are implicitly converted to an int before the arithmetic is done. This means that the result of byte * byte will be int rather than byte as you would expect.

You can see some further explanations and examples here

You can cast the result of the operation back to byte to make the code work, although you should think about what you want to happen if the result of the calculation will no longer fit into a byte (for example 12 will fit into a byte but 12 * 12 will not)

codebox
  • 19,927
  • 9
  • 63
  • 81