Why byte and short division results in int in Java?

后端 未结 5 763
孤城傲影
孤城傲影 2020-12-21 10:14

In Java, if we divide bytes, shorts or ints, we always get an int. If one of the operands is long, we\'ll ge

5条回答
  •  时光说笑
    2020-12-21 10:26

    Whenever you're defining a variable of type byte, whatever you type across from it should be of type byte.

    That means it can only be a number in the range of a byte (-128 to 127).

    However, when you type in an expression, for ex. byteA/byteB that is not the same as typing in a literal, for ex. the number 127.

    This is the nature of Java - the integer is the default data type used for whole numbers.

    By default when you're making an assignment of an expression, Java converts that into the default data type (integer) despite the fact that the result of the expression might be a valid value for a byte.

    So what happens is that when you define a byte and assign an expression as the value of that byte, Java will need to convert it into an integer:

    int byteAByteB = byteA / byteB;
    

    However, you can get around that by casting the assigned expression and thus forsing Java to treat it as a byte.

    byte byteAByteB = (byte) (byteA / byteB);
    

    This way you're telling Java to treat that as a byte. (Can also be done with short, etc.)

提交回复
热议问题