[java] What does the "+=" operator do in Java?

Can you please help me understand what the following code means:

x += 0.1;

This question is related to java

The answer is


As many people have already pointed out, it's the XOR operator. Many people have also already pointed out that if you want exponentiation then you need to use Math.pow.

But I think it's also useful to note that ^ is just one of a family of operators that are collectively known as bitwise operators:

Operator    Name         Example     Result  Description
a & b       and          3 & 5       1       1 if both bits are 1.
a | b       or           3 | 5       7       1 if either bit is 1.
a ^ b       xor          3 ^ 5       6       1 if both bits are different.
~a          not          ~3          -4      Inverts the bits.
n << p      left shift   3 << 2      12      Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p      right shift  5 >> 2      1       Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p     right shift  -4 >>> 28   15      Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

From here.

These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.


In java the default type of numbers like 2 or -2(without a fractional component) is int and unlike c# that's not an object and we can't do sth like 2.tostring as in c# and the default type of numbers like 2.5(with a fractional component) is double; So if you write:

short s = 2;
s = s + 4;

you will get a compilation error that int cannot be cast into short also if you do sth like below:

float f = 4.6;
f = f + 4.3;

you will get two compilation errors for setting double '4.6' to a float variable at both lines and the error of first line is logical because float and double use different system of storing numbers and using one instead of another can cause data loss; two examples mentioned can be changed like this:

s += 4
f += 4.3

which both have an implicit cast behind code and have no compile errors; Another point worthy of consideration is numbers in the range of 'byte' data type are cached in java and thus numbers -128 to 127 are of type byte in java and so this code doesn't have any compile errors:

byte b = 127

but this one has an error indeed:

byte b = 128

because 128 is an int in java; about long numbers we are recommended to use an L after the number for the matter of integer overflow like this:

long l = 2134324235234235L

in java we don't have operator overloading like c++ but += is overloaded only for String and not for the let's say StringBuilder or StringBuffer and we can use it instead of String 'concat' method but as we know String is immutable and that will make another object and will not change the same object as before :

String str = "Hello";
str += "World";

It's fine;


As already stated by the other answer(s), it's the "exclusive or" (XOR) operator. For more information on bit-operators in Java, see: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html


It's one of the assignment operators. It takes the value of x, adds 0.1 to it, and then stores the result of (x + 0.1) back into x.

So:

double x = 1.3;
x += 0.1;    // sets 'x' to 1.4

It's functionally identical to, but shorter than:

double x = 1.3;
x = x + 0.1;

NOTE: When doing floating-point math, things don't always work the way you think they will.


^ is binary (as in base-2) xor, not exponentiation (which is not available as a Java operator). For exponentiation, see java.lang.Math.pow().


It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.

ex :-

To use your example:

The binary representation of 5 is 0101. The binary representation of 4 is 0100.

A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

0101 ^ 0100 = 0001 (5 ^ 4 = 1) .


XOR operator rule

0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows -

a = 0011 1100

b = 0000 1101



a^b ==> 0011 1100  (a)
        0000 1101  (b)
        -------------  XOR
        0011 0001  => 49

(a ^ b) will give 49 which is 0011 0001


  • x += y is x = x + y
  • x -= y is x = x - y
  • x *= y is x = x * y
  • x /= y is x = x / y
  • x %= y is x = x % y
  • x ^= y is x = x ^ y
  • x &= y is x = x & y
  • x |= y is x = x | y

and so on ...


XOR operator rule =>

0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1

Binary representation of 4, 5 and 6 :

4 = 1 0 0 
5 = 1 0 1
6 = 1 1 0

now, perform XOR operation on 5 and 4:

     5 ^ 4 => 1  0  1   (5)
              1  0  0   (4)
            ----------
              0  0  1   => 1

Similarly,

5 ^ 5 => 1   0   1    (5)
         1   0   1    (5)
       ------------
         0   0   0   => (0)


5 ^ 6 => 1   0   1  (5)
         1   1   0  (6)
        -----------
         0   1   1  => 3

You can take a look at the bytecode whenever you want to understand how java operators work. Here if you compile:

int x = 0;
x += 0.1;

the bytecode will be accessible with jdk command javap -c [*.class]:(you can refer to Java bytecode instruction listings for more explanation about bytecode)

0: iconst_0 //  load the int value 0 onto the stack
1: istore_1 //  store int value into variable 1 (x)
2: iload_1 // load an int value from local variable 1 (x)
3: i2d // convert an int into a double (cast x to double)
4: ldc2_w        #2                  // double 0.1d -> push a constant value (0.1) from a constant pool onto the stack
7: dadd //  add two doubles (pops two doubles from stack, adds them, and pushes the answer onto stack)
8: d2i // convert a double to an int (pops a value from stack, casts it to int and pushes it onto stack)
9: istore_1 // store int value into variable 1 (x)

Now it is clear that java compiler promotes x to double and then adds it with 0.1.
Finally it casts the answer to integer .
There is one interesting fact I found out that when you write:

byte b = 10;
b += 0.1;

compiler casts b to double, adds it with 0.1, casts the result which is double to integer, and finally casts it to byte and that is because there is no instruction to cast double to byte directly.
You can check the bytecode if you doubt :)


AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.

The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.

To use your example:

  • The binary representation of 5 is 0101.
  • The binary representation of 4 is 0100.

A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

With 4 and 5, the only difference is in the last place; so

0101 ^ 0100 = 0001 (5 ^ 4 = 1) .


In other languages like Python you can do 10**2=100, try it.


devtop += Math.pow(x[i] - mean, 2); will add the result of the operation Math.pow(x[i] - mean, 2) to the devtop variable.

A more simple example:

int devtop = 2;
devtop += 3; // devtop now equals 5

It increases the value of the variable by the the value after +=. For example:

float x = 0;
x += 0.1;
//x is now 0.1
x += 0.1;
//x is now 0.2

It's just a shorter version of:

x = x+0.1;

As others have said, it's bitwise XOR. If you want to raise a number to a given power, use Math.pow(a , b), where a is a number and b is the power.


The ^ operator in Java

^ in Java is the exclusive-or ("xor") operator.

Let's take 5^6 as example:

(decimal)    (binary)
     5     =  101
     6     =  110
------------------ xor
     3     =  011

This the truth table for bitwise (JLS 15.22.1) and logical (JLS 15.22.2) xor:

^ | 0 1      ^ | F T
--+-----     --+-----
0 | 0 1      F | F T
1 | 1 0      T | T F

More simply, you can also think of xor as "this or that, but not both!".

See also


Exponentiation in Java

As for integer exponentiation, unfortunately Java does not have such an operator. You can use double Math.pow(double, double) (casting the result to int if necessary).

You can also use the traditional bit-shifting trick to compute some powers of two. That is, (1L << k) is two to the k-th power for k=0..63.

See also


Merge note: this answer was merged from another question where the intention was to use exponentiation to convert a string "8675309" to int without using Integer.parseInt as a programming exercise (^ denotes exponentiation from now on). The OP's intention was to compute 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0 = 8675309; the next part of this answer addresses that exponentiation is not necessary for this task.

Horner's scheme

Addressing your specific need, you actually don't need to compute various powers of 10. You can use what is called the Horner's scheme, which is not only simple but also efficient.

Since you're doing this as a personal exercise, I won't give the Java code, but here's the main idea:

8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
        = (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9

It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.

In table form:

step   result  digit  result*10+digit
   1   init=0      8                8
   2        8      6               86
   3       86      7              867
   4      867      5             8675
   5     8675      3            86753
   6    86753      0           867530
   7   867530      9          8675309=final

It is the XOR bitwise operator.


It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1. So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.


devtop += Math.pow(x[i] - mean, 2); adds Math.pow(x[i] - mean, 2) to devtop.


That is because you are using the xor operator.

In java, or just about any other language, ^ is bitwise xor, so of course,

10 ^ 1 = 11. more info about bitwise operators

It's interesting how Java and C# don't have a power operator.


^ = (bitwise XOR)

Description

Binary XOR Operator copies the bit if it is set in one operand but not both.

example

(A ^ B) will give 49 which is 0011 0001


Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like

  • XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
  • If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
  • Swapping values without using temporary variable
  • Finding missing number in the range 1 to n
  • Basic validation of data sent over the network.

Lot many such tricks can be done using bit wise operators, interesting topic to explore.


It's bitwise XOR, Java does not have an exponentiation operator, you would have to use Math.pow() instead.


It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).