- 1

Null in equal method??help

why do we do null check in equal method? we will obviously put something that is not null for comparison....is there any circumstance that an object could be a null?

1st Nov 2017, 6:49 PM
oyl
8 Antworten
- 1
how do you create the object reference before you create the object itself?could you show me a real example?
1st Nov 2017, 7:16 PM
oyl
+ 4
Nothing more fun than dealing with NullPointerException. The null check helps you plan ahead for such an event and handle it rather than having your program crash out because you're trying to access an object with a null value when it should have a reference to the object instead. Also, we obviously expect everything to simply work how we intend, but that isn't always the case and simply put, things happen. However, if you plan ahead and handle the various things that you can predict that'll go wrong, then you're at least prepared for the "unexpected."
1st Nov 2017, 7:00 PM
AgentSmith
+ 4
Lets say that you create the object reference before you actually create the object itself...and then you forget to create the object. In this case, you have an object with a null reference, and if you use it you'll crash out.
1st Nov 2017, 7:13 PM
AgentSmith
+ 3
MyClass myobj = null; ^That's how you create an object reference before you create the object itself. myobj = new MyClass(); ^That creates an instance of the class, it creates the object and assigns its reference to the variable myobj. In the first example, it creates the reference but it doesn't create the actual object, so there is no reference to it, thus it's null.
1st Nov 2017, 7:55 PM
AgentSmith
+ 2
Lets say I want to see if an Animal is in an array. Animal[] world = // The array contains: {new Snake(), new Dog(), new Pig(), null, null}; /* Where null has not been created yet / is empty room in the world */ Animal obj = new Cat(); Now, is a Cat that is similar to 'obj' already in the array? for(int i = 0; i < world.length; i++) if(obj.equals(world[i])) System.out.println("Already in the Array!"); Notice we will be comparing equality with some null values here.
2nd Nov 2017, 1:57 AM
Rrestoring faith
Rrestoring faith - avatar
- 1
why would an object be a null??could u provide some examples?
1st Nov 2017, 7:02 PM
oyl
- 1
MyClass myobj=null; why would someone write that?
1st Nov 2017, 8:29 PM
oyl