3 Replies Latest reply: Jan 7, 2005 7:23 AM by 797177 RSS

    Difference in b += 100; and b = b + 100;

    807596
      On the java tutorial page on assignment operators, http://java.sun.com/docs/books/tutorial/java/nutsandbolts/assignment.html, the following is mentioned:

      "Suppose you wanted to add a number to a variable and assign the result back into the variable, like this:
      i = i + 2;
      You can shorten this statement using the shortcut operator +=, like this:
      i += 2;
      The two previous lines of code are equivalent. "


      But if this is the case then why the following code gives the compile time error
        byte b = 0;
        b = b + 100;
      Test.java:14: possible loss of precision
      found : int
      required: byte
      b = b + 100;
      ^
      1 error
      where as the following compiles without any error
        byte b = 0;
        b += 100;