top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Wha is the difference between a = a + b and a += b in Java?

+1 vote
2,743 views
Wha is the difference between a = a + b and a += b in Java?
posted Oct 14, 2016 by Anitha

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

1 if data type of both a and b are same then no difference.
2 if data type are not same then compiler return error, if not return error means output is not correct;
Ex 1.

int a = 5
float b=1.7;
a += b;
// a == 6  

Ex 2.

byte a = 1;
int b = 2;

a += b; // compiles
a = a + b; // doesn't compile as a byte + int = int
a = (byte) (a + b); // compiles as this is the same as +=
answer Jan 6, 2017 by Ajay Kumar
one thing you missed brother, you have written
a = a + b; // doesn't compile as a byte + int = int (point 2 in your ans) but
this is not true always example:
if you interchange the type like
a = a + b; //  compile as a int=int+byte
so now it is not a lossy conversion and return output successfully.  follow this compiled link :
http://ideone.com/yZSSIz
+3 votes

Hi Anitha the arithmetic expression a+=b is a type of compound assignment operator and according to java language specification,I found that this expression is evaluated as :
"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." Example :

     /* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        short a=3;
        double b=3.6;
        System.out.println(a+=b);    // expression is evaluated as a=(short)(a+b); type casting is happening here result is 6
        System.out.println(a=a+b);  //  throws an error : incompatible types: possible lossy conversion from double to short
    }
}

Reference : http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2

answer Oct 14, 2016 by Shivam Kumar Pandey
Thanks for the refference
welcome
Similar Questions
+2 votes

Given 2 strings, a and b, return a string of the form shorterString+longerString+shorterString, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty (length 0). If input is "hi" and "hello", then output will be "hihellohi".

...