Java Solutions

While working with Java the very common and often faced exceptions are as below :

1.NullPointerException:

What is NullPointerException in Java and How to resolve the NullPointerException in Java. How shall I resolve the NullPointerException thrown in Java

Answer: This is the exception class which is thrown by the program when we are trying to reference a variable which is null, or trying to perform a get operation on an object which does not have that value. Trying to access a class or object reference which is not initialized.

Above screenshot is the example of the NullPointerException when on null string the concat operation is performed the exception is thrown. First validation before performing any access operation should be a null check.

2. The ClassCastException 

What is ClassCastException in Java.How to resolve the ClassCastException in Java.How shall I resolve the ClassCastException thrown in Java

Answer: This exception occurs when you are trying to cast a class into another which are not related or their type does not match each other. Generally classes are cast to the parent Interface, class or into the similar object of the same class.

package com.java.files;

public class CheckYourCast implements ClassCastInterface{    @Override

public void castClass() { }

@Override

public void checkException() {  }

public static void main(String[] args) {

 ClassCastInterface Instance= new CastException();

             CastException cast=(CastException)new CheckYourCast();    }}

Result of Run:

Exception in thread “main” java.lang.ClassCastException: com.java.files.CheckYourCast cannot be cast to com.java.files.CastException  at com.java.files.CheckYourCast.main(CheckYourCast.java:15)

3.ArrayIndexOutOfBoundException:

What is ArrayIndexOutOfBoundException in Java.How to resolve the ArrayIndexOutOfBoundException in Java.How shall I resolve the ArrayIndexOutOfBoundException thrown in Java

Answer: This error indicates that you are trying to access an index of the array which is not there . i.e you are trying to perform an operation on an index which is greater than the size of the array. Remember counting in java starts from 0 so if the number of items in array are 5 then the counting of the index will start from 0.
the 0th index will be point to the first item and hence 1th index to the second element.
Thus if an array is to be traversed through a loop then the index shall be compared using the < operator with the length of the array.

Java 8 Salient Features

  1. Using lambda expressions boiler plate code has been reduced.
  2. Addition of the static methods to the Interface.
  3. Introduction of method references and functional interfaces.
  4. Betterment with Date and Time zone handling with temporal adjusters.

Leave a Comment

Your email address will not be published. Required fields are marked *