What One Of The Following Is Best Practice To Handle Null #1163
What one of the following is best practice to handle Null Pointer exception?<br /> i) int noOfStudents = line.listStudents().count;<br /> ii) int noOfStudents = getCountOfStudents(line);</p> <pre><code class="language-java" line="1"> public int getCountOfStudents(List line) { if(line != null) { if(line.listOfStudents() != null) { return line.listOfStudents().size(); } } throw new NullPointerException("List is empty"); } </code></pre>
This multiple choice question (MCQ) is related to the book/course gs gs128 Java. It can also be found in gs gs128 Java Autoboxing - Java Coding Best Practices - Quiz No.1.
What one of the following is best practice to handle Null Pointer exception?
i) int noOfStudents = line.listStudents().count;
ii) int noOfStudents = getCountOfStudents(line);
i) int noOfStudents = line.listStudents().count;
ii) int noOfStudents = getCountOfStudents(line);
public int getCountOfStudents(List line) { if(line != null) { if(line.listOfStudents() != null) { return line.listOfStudents().size(); } } throw new NullPointerException("List is empty"); }
Option (i)
Option (ii)
Compilation Error
Option (ii) gives incorrect result