How to insert rows into Microsoft SQL Database using Java [duplicate] - java

I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?

Straight from the API Specifications for the ClassCastException:
Thrown to indicate that the code has
attempted to cast an object to a
subclass of which it is not an
instance.
So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.

It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
class A {...}
class B extends A {...}
class C extends A {...}
You can cast any of these things to Object, because all Java classes inherit from Object.
You can cast either B or C to A, because they're both "kinds of" A
You can cast a reference to an A object to B only if the real object is a B.
You can't cast a B to a C even though they're both A's.

It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}

Consider an example,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
At Another t5 = (Another) new Goat(): you will get a ClassCastException because you cannot create an instance of the Another class using Goat.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
How to deal with the ClassCastException:
Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.
Source of the Note and the Rest

Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int, via Integer.parseInt("1") -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.

A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
String obj = (String) hmp.get(key);
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.

You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).

A very good example that I can give you for classcastException in Java is while using "Collection"
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.

You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.

Exception is not a subclass of RuntimeException -> ClassCastException
final Object exception = new Exception();
final Exception data = (RuntimeException)exception ;
System.out.println(data);

A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
list.add("two");
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main (ClassCastExceptionExample.java:19)
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.

If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException
For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

Related

Don't know how to fix java.lang.ClassCastException error [duplicate]

I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?
Straight from the API Specifications for the ClassCastException:
Thrown to indicate that the code has
attempted to cast an object to a
subclass of which it is not an
instance.
So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
class A {...}
class B extends A {...}
class C extends A {...}
You can cast any of these things to Object, because all Java classes inherit from Object.
You can cast either B or C to A, because they're both "kinds of" A
You can cast a reference to an A object to B only if the real object is a B.
You can't cast a B to a C even though they're both A's.
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
Consider an example,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
At Another t5 = (Another) new Goat(): you will get a ClassCastException because you cannot create an instance of the Another class using Goat.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
How to deal with the ClassCastException:
Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.
Source of the Note and the Rest
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int, via Integer.parseInt("1") -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
String obj = (String) hmp.get(key);
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.
You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).
A very good example that I can give you for classcastException in Java is while using "Collection"
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
Exception is not a subclass of RuntimeException -> ClassCastException
final Object exception = new Exception();
final Exception data = (RuntimeException)exception ;
System.out.println(data);
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
list.add("two");
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main (ClassCastExceptionExample.java:19)
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException
For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

Class Cast Execption when Trying to Add Object array as Component in Java Swing [duplicate]

I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?
Straight from the API Specifications for the ClassCastException:
Thrown to indicate that the code has
attempted to cast an object to a
subclass of which it is not an
instance.
So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
class A {...}
class B extends A {...}
class C extends A {...}
You can cast any of these things to Object, because all Java classes inherit from Object.
You can cast either B or C to A, because they're both "kinds of" A
You can cast a reference to an A object to B only if the real object is a B.
You can't cast a B to a C even though they're both A's.
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
Consider an example,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
At Another t5 = (Another) new Goat(): you will get a ClassCastException because you cannot create an instance of the Another class using Goat.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
How to deal with the ClassCastException:
Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.
Source of the Note and the Rest
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int, via Integer.parseInt("1") -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
String obj = (String) hmp.get(key);
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.
You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).
A very good example that I can give you for classcastException in Java is while using "Collection"
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
Exception is not a subclass of RuntimeException -> ClassCastException
final Object exception = new Exception();
final Exception data = (RuntimeException)exception ;
System.out.println(data);
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
list.add("two");
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main (ClassCastExceptionExample.java:19)
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException
For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

unable to use GridPane to load fxml file in java [duplicate]

I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?
Straight from the API Specifications for the ClassCastException:
Thrown to indicate that the code has
attempted to cast an object to a
subclass of which it is not an
instance.
So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
class A {...}
class B extends A {...}
class C extends A {...}
You can cast any of these things to Object, because all Java classes inherit from Object.
You can cast either B or C to A, because they're both "kinds of" A
You can cast a reference to an A object to B only if the real object is a B.
You can't cast a B to a C even though they're both A's.
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
Consider an example,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
At Another t5 = (Another) new Goat(): you will get a ClassCastException because you cannot create an instance of the Another class using Goat.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
How to deal with the ClassCastException:
Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.
Source of the Note and the Rest
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int, via Integer.parseInt("1") -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
String obj = (String) hmp.get(key);
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.
You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).
A very good example that I can give you for classcastException in Java is while using "Collection"
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
Exception is not a subclass of RuntimeException -> ClassCastException
final Object exception = new Exception();
final Exception data = (RuntimeException)exception ;
System.out.println(data);
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
list.add("two");
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main (ClassCastExceptionExample.java:19)
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException
For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

Hibernate Cast "arraylist" from List POJO to another POJO? [duplicate]

I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?
Straight from the API Specifications for the ClassCastException:
Thrown to indicate that the code has
attempted to cast an object to a
subclass of which it is not an
instance.
So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
class A {...}
class B extends A {...}
class C extends A {...}
You can cast any of these things to Object, because all Java classes inherit from Object.
You can cast either B or C to A, because they're both "kinds of" A
You can cast a reference to an A object to B only if the real object is a B.
You can't cast a B to a C even though they're both A's.
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
Object -> Animal -> Dog
You might have a method called:
public void manipulate(Object o) {
Dog d = (Dog) o;
}
If called with this code:
Animal a = new Animal();
manipulate(a);
It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.
In later versions of Java you do get a compiler warning unless you do:
Dog d;
if(o instanceof Dog) {
d = (Dog) o;
} else {
//what you need to do if not
}
Consider an example,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
At Another t5 = (Another) new Goat(): you will get a ClassCastException because you cannot create an instance of the Another class using Goat.
Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
How to deal with the ClassCastException:
Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.
Source of the Note and the Rest
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int, via Integer.parseInt("1") -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.
A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
String obj = (String) hmp.get(key);
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.
You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).
A very good example that I can give you for classcastException in Java is while using "Collection"
List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));
for(Object obj:list) {
String str = (String)obj;
}
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
Exception is not a subclass of RuntimeException -> ClassCastException
final Object exception = new Exception();
final Exception data = (RuntimeException)exception ;
System.out.println(data);
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
list.add("two");
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main (ClassCastExceptionExample.java:19)
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException
For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

The compiler will report warning when an instance is casted to a generic type

I can't understand the code below. The complier report a warning. As I know, the generic type is erased. But I don't know why the code will generate a warning. Can anyone help me?
public class Generic<T>{
public void method(){
Object obj = new Object();
T t = (T)obj; // compile warning
}
}
After execute command "javac Generic.java -Xlint:unchecked", the information of warning is printed below
Generic.java:4: warning: [unchecked] unchecked cast
T t = (T) obj; // compile warning
^
required: T
found: Object
where T is a type-variable:
T extends Object declared in class Generic
The compiler issues a warning because it can be dangerous. In particular, it can lead to hard-to-track ClassCastExceptions. Let's see why.
Here's a slightly modified version of your code:
public class Generic<T> {
public T method() {
Object obj = new Object();
T t = (T) obj; // warning
return t;
}
}
Because of type erasure, the JVM can't actually check that obj is an instance of T at runtime; the cast it actually a no-op at runtime. And now consider this method, which takes a Generic<T> and adds its object to a list:
public static <T> void addToList(Generic<T> generic, List<T> list) {
T t = generic.method();
list.add(t);
}
And finally, let's use this addToList method:
List<Integer> integers = new ArrayList<>();
Generic<Integer> genericInt = new Generic<>();
addToList(genericInt, integers);
Integer theInt = integers.get(0); // ClassCastException!
Because of that type erasure, addToList couldn't do any type checking (the T in the method is just compiled to the most specific type that T could be, which in this case is Object because T is unbound). That means that it run successfully, but it put that new Object() ("cast" to T) in what should be a List<Integer>. It all works until you try to get the Integer out, at which point the compiler is forced to try to cast that Object to Integer. That last line compiles down to something like:
Integer theInt = (Integer) (integers.get(0));
And this throws a ClassCastException, since that first element was instantiated as new Object() (and thus isn't an Integer).
In this toy app, it's relatively straightforward to track down the actual problem. But consider a bigger application, where various things are putting elements into the List. Now you get a ClassCastException, and it can be tricky to find the buggy code that put the non-Integer object in the list.
So, that warning about unsafe casts is real -- the compiler is trying to tell you that the cast can't be checked at runtime, and thus is unsafe in that it could lead to hard-to-debug errors.
I saw this question raised by myself two years ago, but now I have already understand it.Firstly modify the define of Generic class like this
public class Generic<T> {
public T method() {
Object obj = new Object();
T t = (T) obj;
return t;
}
}
Then if run the code below.
Generic<String> generic = new Generic<String>();
System.out.println("" + generic.method());
The crash will occur.The information of crash is
Exception in thread "main" java.lang.ClassCastException:
java.lang.Object cannot be cast to java.lang.String

Categories