Java program to Generate classcast exception

Java program to Generate classcast exception

Example 1.

class Shoes {
    // Some shoes properties and methods
}

class Man extends Shoes {
}

public class Main {
    public static void main(String[] args) {
        Shoes shoes = new Shoes();
        // Incorrect casting: shoes cannot be cast to Man
        Man man = (Man) shoes; // This will throw ClassCastException
    }
}


Example 2.

class Patoto {
    }

class Onion extends Patoto {
   
}

public class Main {
    public static void main(String[] args) {
        Patoto patoto = new Patoto();
        // Incorrect casting: Patoto cannot be cast to Onion
        Onion onion = (Onion) Patoto; // This will throw ClassCastException
    }
}

Example 3.

public class MainClassCastException {
    public static void main(String args[]) {
        Object[] array = new String[5];
        
        Integer[] integers = (Integer[]) array; // This will throw ClassCastException Generate Example
    }
}

Example 4.

import java.util.ArrayList;
import java.util.List;

public class MainClassCastExceptionJava {
    public static void main(String[] args) {
        List listObj = new ArrayList();
        listObj.add("Hello Java");
        listObj.add("code pulling");
        
        // Incorrect casting: String can't be cast to Integer Object
        Integer numberObj = (Integer) listObj.get(0); // This will throw ClassCastException Example
    }
}

Example 5.

import java.util.ArrayList;
import java.util.List;

public class MainClassCastException {
    public static void main(String[] args) {
        List<String> listOfString = new ArrayList<>();
        listOfString.add("Java");
        
        // Incorrect casting: String can't be cast to Integer Object
        Integer number = (Integer) strings.get(0); // This will throw ClassCastException Generate Example
    }
}

 

 

Leave a Reply

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