Posts

Showing posts with the label pointer

NPE as well as Null check free code ... Really ?

Image
NPE as well as Null check free code … Really ? Is this how your Java code review start ? NPE is always nightmare for a Java developer. Lets not discussion to much and jump on an usual Java code snippet public interface Service { public boolean switchOn(int timmer); public boolean switchOff(int timmer); //Other controls } public class RefrigeratorService implements Service { // ... } public class HomeServices { private static final int NOW = 0; private static HomeServices service; public static HomeServices get() { //Null Check #1 if(service == null) { service = new HomeServices(); } return service; } public Service getRefrigertorControl() { return new RefrigeratorService(); } public static void main(String[] args) { /* Get Home Services handle */ HomeServices homeServices = HomeServices.get(); //Null Check #2 if(homeServices != null) { Serv...

How to avoid NPE while Auto-Unboxing

Auto-Boxing/Unboxing is introduced in Java 5 version. It supports automatic conversion of primitive type (int, boolean, float, double) to their equivalent Objects ( Integer, Boolean, Float, Double) in assignment , method and constructor invocation and other way also. Here is the examples Auto-Boxing Integer i = 10; // Auto-boxing converts primitive int value to Integer Object Auto-Unboxing int i = 0; i= new Integre(10); // Auto-Unboxing converts Integer Object to primitive int There is serious problem with using Auto-bocing/Unboxing, it may result null pointer exception. Take an example of following program package testproject; public class TestAutoUnboxing { private static TestAutoUnboxing test= new TestAutoUnboxing(); //cause Null Pointer Exception public static final Boolean YES = true; // Autoboxing for private boolean amIHappy = YES; // Instance Variable public static void main(String[] args){ System.o...