Saturday, 12 March 2016

WHY NullPointerException occur and How to Handle NullPointerException in Java

How to Effectively Handle NullPointerException in Java


ans:-NullPointerException is an unchecked exception and extends RuntimeException.
      It doesn’t force you to use catch block to handle it

Q-Why NullPointerException occur in your code?
ans-"NullPointerException is a situation in code where you try to access/ modify an object which has not been initialized yet"
means that object reference variable is not pointing anywhere and refers to nothing or ‘null’.
 A simple example can be:
package com.piyush.npe;
public class SampleNPE {
    public static void main(String[] args) {
        String s = null;
        System.out.println(s.toString()); // s is un-initialized and is null
    }
}



Note:-Common places where NullPointerException usually occur

ans:-NullPointerException can occur anywhere in your code
1:-) Invoking methods on an object which is not initialized.
2:-) Incorrect configuration for frameworks like spring which works on dependency injection
3:-) Parameters passed in a method are null.
4:-) Calling toString() method on object which is null.
5:-) Using synchronized on an object which is null
6:-) Chained statements i.e. multiple method calls in a single statement.
7:-) Comparing object properties in if block without checking null equality.

Q-How to avoid the NullPointerException?

ans:-First ensure that all your objects are initialized properly.
note:-If you are dealing with static variables or static method than you won’t get null pointer exception
Check Each Object For Null Before Using

I listed how to avoid NPE:-
1- Empty Collection
2- Use some Methods
3- assert Keyword
4- Assert Class
5- Exception Handling
6- Too many dot syntax
7- StringUtils Class


1:-) Prefer String.valueOf() method instead of toString().
example:-
package com.piyush.npe;
public class SampleNPE {
    public static void main(String[] args) {
        String s = null;
        System.out.println(String.valueOf(s)); // using String.valueOf(s) we can avoid nullpointerException;
    }
}


2:-) Use annotations @NotNull and @Nullable.

3:-) Empty Collection
Empty collection is collection which hasn’t any elements. Some developers return null value for Collection which has no elements but this is false, you should return Collections.EMPTY_LIST, Collections.EMPTY_SET andCollections.EMPTY_MAP.
example:-
public static List getEmployees() { 
2  List list = Collections.EMPTY_LIST; 
3  return list; 
4} 

4:-)Use some Method
Use some methods to assure that null value not exist like contains(), indexOf(), isEmpty(), containsKey(), containsValue() and hasNext().
example:-
public class Example {
02     private static List<Integer> numbers = null;
03
04     public static List<Integer> getList() {
05          if (numbers == null)
06               return Collections.emptyList();
07          else
08               return numbers;
09     }
10}
 example2:- 
     String myName = "Piyush Kumar  Bangalore"; 
     List list = Collections.EMPTY_LIST;  
     boolean exist = list.contains(myName);  
     int index = list.indexOf(myName);  
     boolean isEmpty =list.isEmpty();  
       
     Map map =Collections.EMPTY_MAP;  
     exist=map.containsKey(myName);  
     exist=map.containsValue(myName);  
     isEmpty=map.isEmpty();  
       
     Set set=Collections.EMPTY_SET;  
     exist=set.contains(myName);  
     isEmpty=set.isEmpty();  
       
     Iterator iterator;  
     exist = iterator.hasNext();

5:-)Exception Handling:-
example:-a- try catch statement
I will change calling code to below code
1String managerId = getManager("A015"); 
2try { 
3  System.out.println(managerId.toString()); 
4} catch (NullPointerException npe) { 
5  //write your code here 
6}
b- Checking of Null values
I will change calling code to below code
1String managerId = getManager("A015"); 
2if (managerId != null) { 
3  System.out.println(managerId.toString()); 
4} else { 
5  //write your code here 
6}
6:-) StringUtils Class
StringUtils class is part of org.apache.commons.lang package, I can use it to avoid NPE specially all its methods are null safe
For example StringUtils. IsEmpty(), StringUtils. IsBlank(), StringUtils.equals(), and much more.
examle:-You can make use of the StringUtils.isNotEmpty, StringUtils.IsEmpty and StringUtils.equals methods, in order to avoid the NullPointerException. For example:
1if (StringUtils.isNotEmpty(str)) {
2     System.out.println(str.toString());
3}

7:-)assert Keyword
8-:) Assert Class


second way:-

How to solve a NullPointerException in Java?

It is simple, put a null check! Surround your object with if statement like
Object mayBeNullObj = getTheObjectItMayReturnNull();
if (mayBeNullObj != null) { // to avoid NullPointerException
mayBeNullObj.workOnIt();
}



Friday, 4 March 2016

How to read a text file and excel sheet in Java?

Q1:-How to read a text file in Java?

ans:-

Solution 1 - Reading File using Scanner:-

Once you imported this class, you can create object of Scanner by passing a FileInputStream to it, pointing to the file you want to read

Scanner provides a method called hasNextLine() which returns true if file has one more line to read.



example:-public class FileReaderDemo{


 public static void main(String args[]) throws IOException
 {

 final String FILE_NAME = "C://temp//xyz.txt"; 

// 1st way to read File in Java - Using 
 Scanner scnr = new Scanner(new FileInputStream(FILE_NAME));
 while (scnr.hasNextLine()) { 

System.out.println(scnr.nextLine()); 
} 
scnr.close();
  }
 }
}


Solution 2 - Reading File using BufferedReader:-


ans:-how to read a file using BufferedReader class. Both classes are defined in java.util package so you need to import them before using it
InputStreamReader actually acts as a bridge between streams and reader classes. Once you have an object of BufferedReader, you can call readLine() method to read the next line from file.



example:-public class FileReaderDemo{


 public static void main(String args[]) throws IOException
 {

 final String FILE_NAME = "C://temp//xyz.txt"; 

// 2nd way to read File in Java - Using BufferedReader BufferedReader buffReader = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME))); 

String line = buffReader.readLine(); 
while (line != null) {
 System.out.println(line);
 line = buffReader.readLine();
       }
   }
 }
Q-How to read XLS and XLSX file in Java?
ans:-


InputStream  inputWorkbook1 = Injecting.class.getClassLoader().getResourceAsStream("data/piyush.xls");
        BufferedReader br = new BufferedReader(new InputStreamReader(inputWorkbook1));
System.out.println("i am in inside file");
Workbook w;
int arrayLength = 0;
int i = 0;
try {

w = Workbook.getWorkbook(inputWorkbook1);
// Get the first sheets

Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
Cell[] cell0 = sheet.getColumn(0);
Cell[] cell1 = sheet.getColumn(1);
Cell[] cell2 = sheet.getColumn(2);

System.out.println(userId + "cell0 --> " + cell0[0].getContents()
+ "\ncell1 -- >" + cell1[0].getContents() + "\ncell2 -- > "


+ cell2[0].getContents());