Honza Brabec
Honza Brabec

Reputation: 37608

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

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)?

Upvotes: 3859

Views: 318698

Answers (12)

Prashant Kumar
Prashant Kumar

Reputation: 290

The += operator in Java is a powerful shortcut that efficiently combines two steps into one. Instead of writing i = i + j, where you need to add i and j and then store the result back in i, you can simply write i += j. This approach not only accomplishes the same task, but it does so with greater efficiency.

What sets += apart is its ability to automatically handle type conversions when necessary. For example, if j is a long—which can represent larger numbers than an int—the += operator seamlessly converts j to int before performing the addition with i. You don't need to explicitly manage these conversions yourself.

This built-in conversion is a result of well-defined rules in the Java language Specification (JLS) that allow it to manage types effectively in these scenarios (This is neither a bug nor an accident, In coding Developer should know what they are coding). Consequently, while both methods achieve the same outcome, using += significantly reduces the risk of type mismatch errors that you might encounter with the more verbose approach.

Here are some examples of using the += operator with different types:

Example 1: byte + int

byte b = 10;
int i = 20;
b += i; // equivalent to b = (byte) (b + i);

In this case, the int value i is converted to a byte before being added to b.

Example 2: short + long

short s = 10;
long l = 20;
s += l; // equivalent to s = (short) (s + l);

In this case, the long value l is converted to a short before being added to s.

Example 3: char + int

char c = 'a';
int i = 1;
c += i; // equivalent to c = (char) (c + i);

In this case, the int value i is converted to a char before being added to c.

Example 4: float + double

float f = 10.5f;
double d = 20.7;
f += d; // equivalent to f = (float) (f + d);

In this case, the double value d is converted to a float before being added to f.

Note that in each of these examples, the += operator performs a narrowing primitive conversion, which may result in a loss of precision or a change in the value of the result.

Upvotes: 0

takra
takra

Reputation: 467

The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do

    int a = 5;
    long b = 10;
    a += b;
    System.out.println(a);

What you're really doing is:

    int a = 5;
    long b = 10;
    a = a + (int) b;
    System.out.println(a);

Upvotes: 28

dinesh028
dinesh028

Reputation: 2187

The problem here involves type casting.

When you add int and long,

  1. The int object is cast to long & both are added and you get a long object.
  2. But the long object cannot be implicitly cast to int. So, you have to do that explicitly.

But += is coded in such a way that it does type casting. i = (int) (i + m)

Upvotes: 65

Umesh Awasthi
Umesh Awasthi

Reputation: 23587

Yes,

basically when we write

i += l; 

the compiler converts this to

i = (int) (i + l);

I just checked the .class file code.

Really a good thing to know.

Upvotes: 184

Lukas Eder
Lukas Eder

Reputation: 221145

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

An example cited from §15.26.2

[...] the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

In other words, your assumption is correct.

Upvotes: 2564

null
null

Reputation: 11879

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Upvotes: 9

Cyborg
Cyborg

Reputation: 193

Subtle point here...

There is an implicit typecast for i+j when j is a double and i is an int. Java ALWAYS converts an integer into a double when there is an operation between them.

To clarify i+=j where i is an integer and j is a double can be described as

i = <int>(<double>i + j)

See: this description of implicit casting

You might want to typecast j to (int) in this case for clarity.

Upvotes: 12

Thirler
Thirler

Reputation: 20760

Very good question. The Java Language specification confirms your suggestion.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

Upvotes: 270

Stopfan
Stopfan

Reputation: 1757

Sometimes, such a question can be asked at an interview.

For example, when you write:

int a = 2;
long b = 3;
a = a + b;

there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.

So to avoid it, you must write your code like this:

int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting

Upvotes: 47

tinker_fairy
tinker_fairy

Reputation: 1361

In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:

 byte -> short -> int -> long -> float -> double. 

The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion

Upvotes: 54

dku.rajkumar
dku.rajkumar

Reputation: 18578

you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like

i = i + (int)l;

or

i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.

but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.

Upvotes: 95

Peter Lawrey
Peter Lawrey

Reputation: 533780

A good example of this casting is using *= or /=

byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57

or

byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40

or

char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'

or

char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'

Upvotes: 510

Related Questions