问题描述:

Let's say I were to have the following line of code:

int number = b/2;

where b is an odd int. What would happen?

Also, if b were instead a long, would java automatically convert this long to an int? What if b were a char, or something else ridiculous?

网友答案:

Java will widen types automatically, but you must narrow the types yourself with a cast.

I suggest you try this for yourself as you might learn something. You can't learn to program without actually doing it at some point.

网友答案:

It will return integer value of b/2 like if b=3 then b/2 will return 1.but if b is long variable say long b=3,then it will return an error saying possible loss precision.

网友答案:

Dividing integers results in an integer which is rounded towards 0. When you start mixing types it depends on if they need widening (will happen automatically) or narrowing (will in most cases not happen automatically).

More details for division can be found in Java Language Specification 15.17.2. Division Operator / and for narrowing and widening at Java Language Specification Chapter 5. Conversions and Promotions.

But I think trying and experimenting in you Java program is a better way to understand than just reading the specification. You will not destroy anything by writing a small test program.

相关阅读:
Top