Search⌘ K
AI Features

Casting

Type casting in Java refers to converting an object or variable from one type to another, which can be categorized into two types: primitive and object casting. Widening casts (implicit) occur when converting from a smaller to a larger primitive type without loss of information, while narrowing casts (explicit) may result in data loss. Object casting necessitates a relationship between classes through inheritance, with upcasting being implicit and downcasting requiring explicit casts. It's essential to note that downcasting can lead to runtime errors if the object does not match the expected subtype.

We'll cover the following...
1.

What is casting?

Show Answer
1 / 2
Java
class Demonstration {
public static void main( String args[] ) {
// Implicit Casts
int i = 5;
char c = 'a';
float f = 5.5f;
// int to double
double d = i;
// char to int
i = c;
// float to double
d = f;
// Explicit Casts
i = (int) (Integer.MAX_VALUE * 2.0d);
System.out.println(i);
byte b = (byte) (100d);
System.out.println(b);
b = (byte) (1000d);
System.out.println(b);
// Not Allowed
// int k = (int)(Boolean.valueOf(true)); <--- compile time error
}
}
1.

Explain reference casting?

Show Answer
Did you find this helpful?
Java
class Demonstration {
public static void main( String args[] ) {
Integer i = new Integer(7);
// Cast i to Number
Number num = i;
// Try to get back i but compiler doesn't
// know if i is a Integer, Double, Byte etc
// so do an explicit cast
Integer k = (Integer) num; // <---
// We let the compiler know that we think
// we are doing the right thing here and the
// code compiles but throws a ClassCastException
// at runtime
// Double d = (Double) num; // <--- compiles but throws a runtime exception
}
}
Technical Quiz
1.

Consider the following set-up:

    class A {

        void print() {
            System.out.println("I am class A");
        }
    }

    class B extends A {

        void print() {
            System.out.println("I am class B");
        }
    }

    class C extends A {

        void print() {
            System.out.println("I am class C");
        }
    }

What will be the output of the following code snippet:

        B b = new B();

        // implicit cast
        A a = b;

        // What will be printed?
        a.print();
A.

I am class A

B.

I am class B

C.

Runtime exception


1 / 2
Java
class Demonstration {
public static void main( String args[] ) {
// Question # 1
B b = new B();
// implicit cast
A a = b;
a.print();
// Question # 2
b = new B();
// implicit cast
a = b;
// Downcast. Uncomment the below line to see
// a ClassCastException being thrown
// C c = (C) a; // <--- ClassCastException thrown
// c.print();
}
}
class A {
void print() {
System.out.println("I am class A");
}
}
class B extends A {
void print() {
System.out.println("I am class B");
}
}
class C extends A {
void print() {
System.out.println("I am class C");
}
}