java.lang.NullPointerException while null integer value to int in java


In this Example we are going to understand the exceptions when we are giving the int value as Integer object null value.

Error Message :
Exception in thread "main" java.lang.NullPointerException
       at com.src.StringOperations.main(StringOperations.java:7)

Error Description :

package com.src;

public class StringOperations {

       public static void main(String[] args) {
              Integer in = null;
              int i = in;
              System.out.println(i);
       }
}
      
      
In the above example ,the red background color line is giving the exception.
Here we are taking Integer object as null. While Integer to int ,the null value can not be changed to int value so we are getting this Nullpointer exception.

Solution:

To avoid this kind of Null Pointer exceptions we can do the null check of the Integer object value.
package com.src;

public class StringOperations {

       public static void main(String[] args) {
              Integer in = null;
              if(in != null) {
              int i = in;
              System.out.println(i);
              }else {
                     System.out.println("Please change the Integer value from null");
              }
       }
}

Output:
Please change the Integer value from nul





Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar