Top 5 Java programming mistakes in interviews

Normally in an interview the candidate is under tremendous pressure and the following mistakes become more likely to happen in such a situation. They are easily avoidable though.

1. Check for null reference before executing any method. Any method argument before being operated upon should be checked for a possible null value. Return or print appropriate message in such cases.


2. Correct usage of conditional and logical operators. Specially >,< and short circuit logical operators (&& and ||). if you are combining null check and empty check , keep in mind that the null check has to be the first half. If it's in any other half, you'll get a NullPointerException.  
 

void doTest(List x){
  if( x != null && !x.isEmpty()){} //is correct 
  if (!x.isEmpty && x != null){} //is error prone
}

 

3. Initialize local variables. Java does not allow any local variables to be used before they are initialized and you should keep this in mind while writing code on paper. Chances are high that you'll miss this.


4. Close all open resources. If you have opened any InputStreams for read/write for any resource, do not forget to close it in the finally block.


5. Be careful while using Iterator.next(). When iterating a collection using an iterator, don't read a value directly from next() method everytime you use it. Hold the value in a variable and use it. Doing a next() everytime makes the iterator shift to the next value. The program will yield incorrect results and can also run into exceptions

void doTest(List x){
  if ( x != null && !x.isEmpty()){
    Iterator i=x.iterator;	
    while(i.hasNext()){
      if(i.next()!= null){
	System.out.println(i.next());
      }
    }
  }
}

Above is not the right way to do this. You will be iterating two values instead of one per loop.

Better way to do this is

void doTest(List x){
  if (x != null && !x.isEmpty()){
    Iterator i=x.iterator;	
    while(i.hasNext()){
      Object o=i.next()
      if(o!=null){
	System.out.println(o);
      }
    }
  }
}

 

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself