Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no need to explicitly cast in case of integers?

byte a=10;
byte b=20;

b=a+b;

In this case, I need to explicitly convert a+b to byte like this :

b=(byte)(a+b);

It's the same with short :

short x=23;
short y=24;

Otherwise it gives an error.

But in case of integers, it's not required to convert explicitly :

int p=7788;
int q=7668;

p=p+q;

This will work just fine.

Why is that?

We don't need to explicitly cast even in the case of long as well.

like image 926
rajkumar.11 Avatar asked Dec 11 '22 02:12

rajkumar.11


1 Answers

If you look at the JLS 4.2.2 Integer Operations, it states that the result of a numerical operation between two integral operands is an int or a long. Since there's no implicit cast from an int to byte or a short, you need an explicit cast.

like image 56
Mureinik Avatar answered Mar 05 '23 06:03

Mureinik