Casting on Expressions [Notes]

Notes from https://www.udemy.com/java-the-complete-java-developer-course/

I hadn’t run into this issue in other languages, but in Java, it turns out that if I have a variable that is statically typed as something other than an int, if such a case has an expression, Java defaults it to int type.

For example:

byte thisByte = -128

byte thisByteByTwo = (thisByte/2)

The resulting error is that it found an incompatible type.  It’s required to have a Byte, but it found an int.  Why an Int? Evidently Java defaults to int type when doing an expression.

The obvious solution is to convert the type, which in Java is called “casting.”  Here’s an example:

byte thisByteByTwo = (byte) (thisByte/2)