Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (20.3k points)

Until today, I thought that for example:

i += j;

Was just a shortcut for:

i = i + j;

But if we try this:

int i = 5;

long j = 8;

Then i = i + j; will not compile but i += j; will compile fine.

Does it mean that in fact i += j; is a shortcut for something like this i = (type of i) (i + j)?

1 Answer

0 votes
by (40.7k points)
edited by

In Java whenever you are trying to add higher data type object to lower data type object, the lower data type object is casted to higher data type object and the end result is always summation of higher data type object. You can’t implicitly cast the higher data type object to lower data type object. It’ll cause incompatible type casting.

In this code, 

int i=5, long j=8; i+=j;

 // Here “+=” does type casting this way i.e. by compiler implicitly uppercasting is done in this manner

 i=(int)((long) i+j);

Whereas, in case of i=i+j; you need to cast explicitly long into int in this way:

i=i+(int)j;

Are you interested in learning Java from scratch! Refer to this video on Java provided by Intellipaat:

So, ideally in Java, type conversion is done to the type of the right variable from the type of left variable as shown below.

Byte-> Short->Int->Long->float->Double

Related questions

0 votes
1 answer
asked Jan 21, 2020 in Java by angadmishra (6.5k points)
0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...