Home > AI > Language > Java >

Object casting in Java

Primitive & Reference variable conversion

a primitive variable contains its value, and conversion of a primitive variable means irreversible changes in its value:

@RunWith(SpringRunner.class)
class Demo11ApplicationTests {


    @Test
    void hello() {
        double myDouble = 1.1;
        int myInt = (int) myDouble;

        assertNotEquals(myDouble, myInt);
    }

}

Reference variables are different; the reference variable only refers to an object but doesn’t contain the object itself.

And casting a reference variable doesn’t touch the object it refers to but only labels this object in another way, 

Upcasting

Casting from a subclass to a superclass is called upcasting

Leave a Reply