What's the difference between = & ==?


One of the most common programming mistakes that one can make is to confuse the equal sign (=) with a double equal signs (==). While experienced programmers can still make the same mistake, knowing the difference between the two is a good way to avoid it.

When we wish to assign a value to a variable or member, we use the equals sign (=). As an example, the following would assign the value of three to the variable a.

a = 1 + 2; // assignment operation

When we wish to make a comparison, such as in an if statement, we use the double equals sign (==). A simple example would be the following

if ( a == b ) then System.out.println ("Match found!");

Now consider what would have happened if we used an assignment operator instead. A would be assigned the value of B - destroying the current contents of A and giving us an incorrect comparison. Finding this type of error can be difficult, because the two operators look so similar. So why does Java use such confusing operators? Java draws its roots from C, which shares the same problem. Unfortunately, its something that all Java programmers must learn to live with.