+ 7

Why not a compilation error?

Can someone please explain: int n1 = Math.pow(3,4) --> compilation error int n2 = 0; n2 += Math.pow(3,4) --> no error why java only cast to integer in the later expression?

4th Jul 2019, 5:01 PM
Mind To Machine đŸ’»đŸ•†
Mind To Machine đŸ’»đŸ•† - avatar
5 Respostas
+ 13
Mind To Machine đŸ’»đŸ•† might you mean n2 in place of n, It is behaving like implicit conversation, good link for it where it is explained very nicely https://stackoverflow.com/questions/2696812/varying-behavior-for-possible-loss-of-precision thats interesting I was not knowing about it previously.
4th Jul 2019, 6:01 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 10
int n1= (int)Math.pow(3,4); it will work correctly, as Math.pow() returns a double type value, and we are trying to assign it to integer type variable, so we need to do explicit typecasting. what is datatype of variable n ?
4th Jul 2019, 5:48 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
Gaurav Agrawal i understand that part but why you dont get an error for the second part? int n2 = 0; n2+= Math.pow(3,4) edit: i checked my post and realize it was not what i meant. i meant " why NOT a compilation error?"
4th Jul 2019, 5:51 PM
Mind To Machine đŸ’»đŸ•†
Mind To Machine đŸ’»đŸ•† - avatar
+ 5
Gaurav Agrawal me again 😅, i meant n2
4th Jul 2019, 6:02 PM
Mind To Machine đŸ’»đŸ•†
Mind To Machine đŸ’»đŸ•† - avatar
+ 5
Gaurav Agrawal thanks for the link now i understand
4th Jul 2019, 6:06 PM
Mind To Machine đŸ’»đŸ•†
Mind To Machine đŸ’»đŸ•† - avatar