Casa > W > What's The Difference Between A = And == In Java?

What's the difference between a = and == in Java?

“=” is for assigning a value to a variable. For example,

  1. 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,

  1. int a=5; 
  2. 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,

  1. int a=5; 
  2. int b=5; 
  3. if(a==b) 
  4. System.out.println(“yes”); 

Above statement will print yes.

But to make you more confused. Try this below code.

  1. String obj1 = new String("xyz");  
  2. String obj2 = new String("xyz");  
  3. if(obj1 == obj2)  
  4. System.out.println("obj1==obj2 is TRUE"); 
  5. else  
  6. 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:

  1. 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:

  1. String obj1 = new String("xyz");  
  2. String obj2 = obj1;  
  3. if(obj1 == obj2)  
  4. System.out.printlln("obj1==obj2 is TRUE");  
  5. else  
  6. 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:

  1. obj1==obj2 is TRUE 

Reference:

What's the difference between equals() and ==?

De Philip Menzies

Qual é o melhor navegador, o Brave ou o navegador de Internet da Samsung? :: O envio de fotos por e-mail reduz a sua qualidade?