What's the difference between a = and == in Java?
“=” is for assigning a value to a variable. For example,
- int a=5;
here you are assigning value 5 to a variable named ‘a’. You can also assign a variable to a variable. (Actually you are assigning value of one variable to the other variable). For example,
- int a=5;
- int b=a;
Same for other data types like String, Float, Double etc.
The “==” operator compares the objects’ location(s) in memory (Not the value)
For example,
- int a=5;
- int b=5;
- if(a==b)
- System.out.println(“yes”);
Above statement will print yes.
But to make you more confused. Try this below code.
- String obj1 = new String("xyz");
- String obj2 = new String("xyz");
- if(obj1 == obj2)
- System.out.println("obj1==obj2 is TRUE");
- else
- System.out.println("obj1==obj2 is FALSE");
Take a guess at what the code above will output. Você adivinhou que ele irá sair obj1==obj2 é VERDADEIRO? Bem, se você adivinhou, então você está realmente errado. Even though the strings have the same exact characters (“xyz”), The code above will actually output:
- obj1==obj2 is FALSE
Are you confused? Bem, vamos explicar melhor: como mencionamos anteriormente, o operador "==" está realmente verificando se os objetos da string (obj1 e obj2) se referem exatamente à mesma localização de memória. Em outras palavras, se ambos obj1 e obj2 são apenas nomes diferentes para o mesmo objeto então o operador "==" irá retornar verdadeiro quando comparar os 2 objetos. Another example will help clarify this:
- String obj1 = new String("xyz");
- String obj2 = obj1;
- if(obj1 == obj2)
- System.out.printlln("obj1==obj2 is TRUE");
- else
- System.out.println("obj1==obj2 is FALSE");
Note in the code above that obj2 and obj1 both reference the same place in memory because of this line: “String obj2 = obj1;”. And because the “==” compares the memory reference for each object, it will return true. And, the output of the code above will be:
- obj1==obj2 is TRUE
Reference:
What's the difference between equals() and ==?