title: Why this code for addition(using bitwise operation) works in java
body: <pre><code>public int add(int a, int b){  
          while (b != 0){
              int carry = (a &amp; b) ;
  
              a = a ^ b; 
  
              b = carry &lt;&lt; 1;
          }
          return a;
   }
  </code></pre>
  
  <p>This is the code to calculate sum of two integers using bitwise operation.</p>
  
  <p>If i calculate manually/programmatically, i see it works for every integer.
  But i am not able to figure out any relation between intermediate value of <code>a</code> and <code>carry</code>.
  and why carry is multiplied by 2 to assign to <code>b</code>? </p>
  
  <p>PS: I found the one answer here
  <a href="https://stackoverflow.com/questions/4895173/bitwise-multiply-and-add-in-java">Bitwise Multiply and Add in Java</a>
  but this is for multiplication and not for addition.</p>