Exactly what Small Clanger said.
Some languages (BASIC being one) allow you to use “=” with impunity everywhere.
a = 27
if a = 9 then
'perfectly good syntax
end if
These languages are smart enough to see the context of the single “=” and say “He is obviously comparing these two things” or “He is obviously assigning a new value to the thing on the left” This doesn’t mean that C++ and Java are backwards since BASIC got it right years ago; rather, introducing objects complicates issues somewhat.
Even BASIC, with its friendly context sensitive interpretation of “=”, used to require the developer to explicitly distinguish between the two purposes. Once upon a time, in order to assign a value in BASIC, one was required to use the “let” keyword:
LET a = 27
That was enough to make sure the compiler knew exactly what you intended. They added the context sensitive bit later on so that you didn’t need to type “let” all over the place.
FORTRAN also distinguishes between assignment and comparison:
Assignment: LET A = 10
Comparison: A.EQ.10
The “==” is simply a modern replacement for FORTRAN’s “.EQ.” operator.
Now to revisit the Java string comparison problem…
The problem here is that Java objects (and strings are objects) are simply references: a pointer to a place in memory where the thing lives.
Java interprets “==” comparison between two object references very literally: It says that the two things (object references) are the same if they point to the same memory location. Keep in mind that “==” works perfectly well for standard integers, booleans, bytes, floats and such.
This is a highly restrictive comparison. Consider my prior example of a “Car” object. The Java “==” comparison will say two cars are the same if and only if they have the same VIN. We really want a smarter kind of equality check that can say “these cars are the same since they have the same motor, make, model, color even though they are distinct vehicles that live in different locations in memory”
In short:
[ol][li]"=" is for assignment only[/li][li]"==" is for very literal equality comparison. It works great for numbers and bytes, but it is usually wrong for objects (in Java)[/li][li]“myObject.equals(yourObject)” is the clumsy thing we are left with for comparing objects in a smart way.[/li]C++ has a much fancier “==” that we can override with our own code to skip the syntax nonsense of point 3.[/ol]