QNA > 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. Avete indovinato che produrrà obj1==obj2 è VERO? Beh, se l'avete fatto, allora vi sbagliate di grosso. Even though the strings have the same exact characters (“xyz”), The code above will actually output:

  1. obj1==obj2 is FALSE 

Are you confused? Bene, spieghiamo meglio: come abbiamo detto prima, l'operatore "==" sta effettivamente controllando per vedere se gli oggetti stringa (obj1 e obj2) si riferiscono esattamente alla stessa posizione di memoria. In altre parole, se sia obj1 che obj2 sono solo nomi diversi per lo stesso oggetto, allora l'operatore "==" restituirà true quando confronta i 2 oggetti. 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 ==?

Di Cirri Cousey

Perché il browser UC è il re dei browser per cellulari? :: Qual è il miglior browser, Brave o il browser Internet Samsung?
Link utili