What is the difference using a += b and a += (int)b ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is the difference using a += b and a += (int)b ?

public class Program{ public static void main(String[] args) { int a = 2; double b = 2.7; b += a; a += (int)b; System.out.println(a); } } I have this code, the output is 6, but I don't understand the difference between a += b and a += (int)b, the output is the same, so, is not necessary in this case to use a += (int)b ?

27th May 2017, 10:22 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
2 Answers
+ 2
So after re-reading the question I may have re-editted my post a bunch 😜. a += b; is an 'automatic' convertion. The compiler will be able to interpret the result as an int due to the +=. However if you did a = a + b, that will for sure throw an error. So a += b is equivalent to: a = (int)(a + (b)); a = a + b; will throw an error because an int cannot be given the value of a double. So, you need to cast the double to an int, which will give you: a = a + (int) b; Just note a += (int) b Might actually be the same as: a = (int) (a +((int) b)); Though, I'm not 100% sure about this, since the compiler could be aware and just ignore the extra conversion.
27th May 2017, 10:41 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
In both cases the code is downcasting the value in b from double to int. But doing it this way: a += (int)b - is preferable because it makes your intentions explicit.
27th May 2017, 10:45 PM
Ulisses Cruz
Ulisses Cruz - avatar