You can omit the part saying !='null entirely and add the referenced object name to the query
Some sample code that will do this:
String object1Meta = Object1.entityName.toString();
String object2Meta = Object2.entityName.toString();
String relationMeta = Object1.MemberNames.Object1_Object2.toString();
List<IMendixObject> objects = Core.retrieveXPathQueryEscaped(this.getContext(), "//%s[%s/%s]", object1Meta, relationMeta, object2Meta);
System.out.println("printing all object 1 descriptions for object 1's which have a relation to an object 2");
for (IMendixObject iMendixObject : objects)
System.out.println("object description: " + iMendixObject.getValue(Object1.MemberNames.Object1Description.toString()));
To invert this (to get all objects WITHOUT a reference) you can do this:
List<IMendixObject> objects = Core.retrieveXPathQueryEscaped(this.getContext(), "//%s[not (%s/%s)]", object1Meta, relationMeta, object2Meta);
To simplify the first example, you could put all parameters hardcoded in the query like this:
List<IMendixObject> objects = Core.retrieveXPathQuery(this.getContext(), "//MyFirstModule.Object1[MyFirstModule.Object1_Object2/MyFirstModule.Object2]");
You will run into trouble if you rename anything in your model though.