A == B vs B == A, What are the differences

So, a short story. The professor asked this question in the classroom as a discussion starter. Beyond the obvious

B = new SomeClass("B"); // But B can be null, can can be new SomeClass("A"); A = new SomeClass("A"); A==B 

doesn't guarantee no NPE when comparing, what are the reasons for using B == A instead of A == B?

Where A and B are of the same type, and it is language independent. So you can assume A.equals (B) for Java, or equivalent syntax in C or C ++, etc.

And no, this is not homework.

0
java c # programming-languages
source share
5 answers

In Java, A == B and B == A always have the same semantics. In C # (which has operator overloading), there might be a difference if, for example, B is an instance of a subclass of class A

Note that A.equals(B) not equivalent to A == B

+10
source share

Commutability is not guaranteed in C # operators, since they can be overloaded, so A == B will not necessarily return the same result as B == A.

eg.

  class Program { static void Main(string[] args) { var a = new MyClass("A"); var b = new MyClass("B"); Console.WriteLine(a == b); Console.WriteLine(b == a); Console.ReadLine(); } public class MyClass { private string _Name; public MyClass(string name) { if (_FirstInstance == null) { _FirstInstance = this; } this._Name = name; } private static MyClass _FirstInstance = null; public static bool operator ==(MyClass left, MyClass right) { return object.ReferenceEquals(left, _FirstInstance); } public static bool operator !=(MyClass left, MyClass right) { return !(left == right); } } 

Yes, I understand that this is crazy.

+3
source share

I think you mean .equals , not == . a.equals(b) will call NPE if a is null, but not if b is null. Therefore, if you know that a not null, you should do a.equals(b) , and not vice versa.

This, however, is language independent. Some languages ​​do not matter at all!

+1
source share

In java you can do A == B or B == A and you will not get NPE. The real problem is when you do

 String s = ...; boolean isNull = s.equals("myString"); 

instead

 boolean isNull = "myString".equals(s); 

Since you are calling a method on an object, and "myString" is a properly created object, then the second call will never throw an NPE, regardless of whether the variable "s" is null or not. You will not get this guarantee on the first call, since you are not sure that the "..." on the right side of "s" is assigned to "yourString" or null.

+1
source share

In java

 Object a = new Object(); Object b = null; System.out.println(a.equals(b)); //false System.out.println(b.equals(a)); //NPE! 

So, if you have a known constant value, it should be on the left side of the expression.

0
source share

All Articles