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. 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:
- 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:
- 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 ==?