Tuesday, June 23, 2020

Common mistakes that most of the programmers may tend to do and tips to avoid the same problems while coding

As a developer , I have observed that one should note that making mistakes are not at all bad. In fact its really good for helping programmers to realize and understand the problems more better and have clear visibility on the problematic areas and that will help situations and improve their programming skills better as well.

Its always good and important to learn lessons from our mistakes and others mistakes which you have noticed surrounded by your team or other teams as well . And the more mistakes you made at the career initial stage the more lessons you can learn and more experience ( wisdom) you can learn. 

Those experiences will help you to have more strength to face the critical situations that you may encounter in future.Also you can handle tough situations with ease in a better and generic approach to resolve the problems .

Facing common problem with Null (NullPointerException):

NullPointerException is thrown when program attempts to use an object reference that has the null value. NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. 

Below are the basic scenarios where we may encounter the NullPointerExceptions :

  • If you are trying to invoking(calling) a method from a null object.
  • In case if you are trying to modifying or accessing a object's field which is null(Means object value is null)
  • If you are trying to get the length of null ,as if it is an array.
  • When you trying to synchronize over a null object.

What is null and why we need it?

Null is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable.

While implementing data structures like linked list and tree we will make use of null. Also in general the null will be using in  Null Object pattern  and Singleton pattern. As we are very much know the Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.

String literal comparison which leads to NullPointerException:       

In java a very common case problem involves the comparison between a String variable and a literal. The String literal may be a String or an element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal.


Out put :


Fix : We can avoid NullPointerException by calling equals on literal rather than object.




Out Put :



Tips to avoid the NullPointerException:

When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them.