java.lang.ClassCastException while Integer to String conversion in java


In this Example we are going to understanding the exception, whiletypecasting the object to String.

Error Message :
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
       at com.si.exceptions.ClassCastExceptionSample.main(ClassCastExceptionSample.java:7)

Error Description :

package com.si.exceptions;

public class ClassCastExceptionSample {

       public static void main(String[] args) {
              Object obj = 4;
              System.out.println((String)obj);
       }
}

      
      
In the above example ,the red background color line is giving the exception.
Here we are assigning integer 4 to the Object.while printing we are typecasting the object to String,means we are converting the int to String which is causing the ClassCastException.

Solution:


To avoid this exception We are using String to Object Conversion method like String.Value(Object) . This will automatically convert this int object to String object shown in green color code as shown below.

package com.si.exceptions;

public class ClassCastExceptionSample {

       public static void main(String[] args) {
              Object obj = 4;
              System.out.println(String.valueOf(obj));
       }
}

Output:
4

4.0

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