Yogesh Patel Yogesh Patel - 16 days ago 5
Java Question

Difference between Scan scan = null; and Scan scan = new Scan();

I am curious to know what difference does it make when I use

Scan scan = new Scan();
instead of
Scan scan = null;


public Scan getScanByColumn1(byte[] columnFamily,Map<String,String> columnMap){
Scan scan = null;
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_SOFTWARE_VERSION);
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_CNUM);
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_SID);
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_HIERARCHY);
return scan;
}

public Scan getScanByColumn2(byte[] columnFamily,Map<String,String> columnMap){
Scan scan = new Scan();
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_SOFTWARE_VERSION);
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_CNUM);
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_SID);
scan.addColumn(columnFamily, ForesightConstants.QUALIFIER_HIERARCHY);
return scan;
}


When I used
Scan scan = null;
It gives warning when i add first column to the scan object. And the warning is
Null pointer access: The variable scan can only be null at this location
.

So, someone please help me find out why am i getting this warning, My program is running fine with Second one but, just curious to find out the reason behind the warning.

Thanks in advance.

Answer

The difference is that if you attempted to run the first version, your program would crash with a NullPointerException (aka NPE) at the first scan.addColumn(...) call.

When you call an instance method, you need an object to call the instance on. But when you initialize scan like this:

  Scan scan = null;

you are setting its value to a null reference ... which means "no instance". And when you then attempt to call the addColumn method on the null reference, you will get an NPE.

That is what the compiler error message is trying to tell you. The compiler can see that though your program is valid Java ... it will crash when you run it.

Comments