Header Ads

Golden Rules for Type Casting While Working With Arithmetic Operator

image credit:devcentral.f5.com
Arithmetic Operators:
In java +,-,*,/,% are called arithmetic operators.Arithmetic operator is used on two operand of same type or different  types(applicable)

Like-
int a=10;
int b=10;
int c=a+b;
System.out.print(c);

output-20
But if we take some different example like--
int a=10;
double b=10.00;
int c=a+b;
System.out.print(c);


output:
possible loss of precision
found : double
required: int
int c=a+b;
         ^
Now this looks very confusing. Is n't? in variable b we are only assigning value 10, which can be considered  as valid int. still compiler is not approving the arithmetic operations.

if you are thinking that the second case failed as the operand types are different and first case passed as two operands were of same type, please check out the below code

byte a=10;
byte b=20;
byte c=a+b;
System.out.print(c);

output:
possible loss of precision
found : int
required: byte
byte c=a+b;
            ^
The most confusing part is the two operand are of type(byte) but still compiler found int type.
Java compiler is too complicated???

Arithmetic Operators Rule:
Let us see the data types (primitive ) in java..

datatypes as per capacity byte being smallest and double being the highest


If we apply any arithmetic operator between two operands say x,y then the result type should follow the below written rule

MAX(int,datatype of first operand,datatype of second operand)

so for all arithmetic operation the above rule will be applicable..
lets take the third example...
byte a=10;
byte b=20;
byte c=a+b;
System.out.print(c);

so for this case--the right side datatype evaluation will be..
as per rule-
Max(int,byte,byte)
Now as per the diagram among int,byte and byte the max is int, hence the right hand side datatype evaluation will be int.
please check the compiler error message--found int.
the second point is here the int is being assigned to byte whose capacity is  lower than int. So compiler is rightly pointing out--"possible loss of precision"

For a quick reference let us see the output datatype for few mixed case..
Datatypes of first operand and second operand output datatype
byte+byte int
byte+short int
char+char int
long+int long
float+long float
double+int double
double+any double

The only thing if one of the data type is string then these rules will not be applicable.
Thats it!!!


Powered by Blogger.