Java J2ee Classes Kothrud Pune
We provide java j2ee classes and live project industrial training. Classes are taken by working professional
How to Effectively Handle NullPointerException in Java
NullPointerException is an unchecked exception and extends RuntimeException.It doesn’t force you to use catch block to handle it.NullPointerException is very much like a nightmare for most of java developer community.
Sections in this post:
# Why NullPointerException occur in your code
# Common places where NullPointerException usually occur
# Best ways to avoid NullPointerException
# Available NullPointerException safe operations
# Why NullPointerException occur in your code
NullPointerException is a situation in code where you try to access/ modify an object which has not been initialized yet.
It essentially means that object reference variable is not pointing anywhere and refers to nothing or ‘null’.
# Common places where NullPointerException usually occur
Well, NullPointerException can occur anywhere in your code for various reasons but i have prepared list of most frequent places based on my experience:
1) Invoking methods on an object which is not initialized
2) Parameters passed in a method are null
3) Calling toString() method on object which is null
4) Comparing object properties in if block without checking null equality
5) Incorrect configuration for frameworks like spring which works on dependency injection
6) Using synchronized on an object which is null
7) Chained statements i.e. multiple method calls in a single statement
This is not an exhaustive list. There are several other places and reasons also.
If you can recall any such other, please leave a comment. it will help others (beginners) also.
Best ways to avoid NullPointerException
1) Ternary Operator boolean expression ? value1 : value2;
2) Use apache commons StringUtils for String operations
3) Check Method Arguments for null very early
4) Consider Primitives Rather than Objects
5) Carefully Consider Chained Method Calls ref.method1().method2().method3().methods4();
6) Use String.valueOf() Rather than toString()
7) Avoid returning null from your methods
8) Discourage Passing of Null Parameters
9) Call String.equals(String) on ‘Safe’ Non-Null String
# Available NullPointerException safe operations
1) instanceof operator
2) Accessing static members of a class
06/08/2018
06/07/2018
Hi All ,
We are JAVA J2EE CLASSES ,KOTHRUD,PUNE
Starting New JAVA/J2EE Morning batch from 9July 7:30 AM to 9:00 AM
Fees: 8000 only
You can Attend 3-4 Free demo .
Syllabus:
Core Java ,JDBC,Ad.Jva , Servlet,JSP, Spring(IOC,APO,MVC,TRASACTION,SECURITY),Hibernate,Web service,Spring Boot.
About Trainer:
9+Experience Currently Working.
Real time Senario only. Live project Training.
For More Details Visit:
http://www.javaj2eeclasses.com
call On: 9067176516.
Click here to claim your Sponsored Listing.
Contact the business
Telephone
Address
OFFICE NO-4 NARANG CORNER CTS 405 NEAR KOTHRUD BUS STAND
Pune
411029