Deep
Deep

Reputation: 959

casting or data type conversion of primitive values

a) If I write something like this in java

short a = 15
short b = 3;
short c = a * b;//will not compile

I know it will not compile because short values are automatically
promoted to int with the resulting value of type int so this will compile:

int d=a*b ; //compile

B)If I do a multiplication of long numbers such as:

long a=15;
long b=3;
long c=a*b;//will compile
int d=a*b;//will not compile

I assume that long values do not get promoted to int because int is smaller,but also when I write

long a=15;

Java would have interpreted the literal as an int because there is no 'l' with 15 in assignment,if java had interpreted it as int why can't it multiply interpreting it as of int data types

int d=a*b; 

Why should this give an error?

Does java not take into consideration the int value in case of any arithmetic operation of long variables ?

Why java allows long a=15; interpreting it as int when I can't do any operation on it as int .

Upvotes: 1

Views: 78

Answers (1)

Karles
Karles

Reputation: 50

This is due to the fact that java converts upwards but not downward. It will convert to something bigger by adding space but by reducing space you might have loss of data therefore java will not do it. It will take your small number like 15 into a long but this is a waste of memory to do so if your never going to fill in the space a long uses.

Upvotes: 2

Related Questions