What Is Casting Upcasting and Downcasting in Java?

What Is Casting Upcasting and Downcasting in Java?

A type cast takes a value of one type and produces the value of another type. Assigning the resultant to a higher type is automatic. The automatic conversion is called type coercion.

The relationship between the base class and the derived class is called casting. The derived class is a type of base class. Also when there is a need to store a value of one type into another type of variable, we need to case the values into the new container type.Java will change one type of data into another when appropriate.

In java casting(upcasting) is safe with the exception that when we perform so called narrowing conversion(a data type that can hold more data to one which can not hold that much data), we run a risk of losing information. Here the compiler forces us to do a cast -in effect saying “This can be a dangerous thing to do” if we want the compiler to do it anyway, we must make the cast explicit.

With a widening conversion, an explicit cast is not needed because the new type will hold more information than old, hence no information is lost. Java allows casting primitive to another except boolean. The class type does not allow casting to convert one to another. There should be special methods.

Due to inheritance, all methods in the base class are available to the derived class or child class. So any message we sent to the base class can also be sent to derived class or child class.

lets us check an example:

//parent class
class Shape{
public void calculateArea(){
public static void createShape(Shape i)
//Rectangle object is a Shape as they have same interface
public class Rectangle extends Shape{
    public static void main(String args[])
        Rectangle rect=new Rectangle();

The base class Shape has a method -calculate area() so as the child class-Rectangle.createShape() method accepts a Shape reference. In Rectangle class the main method call createShape() by providing the Rectangle object.

See also  Class ParsePosition in Java

Java is popular for type checking but in this case, it accepts another type. But here Rectangle is a Shape object and there is no method that createShape() could call for an instrument that is not in Rectangle class. Inside createShape(), the code works for Shape and anything derived from Shape. The act of converting a Rectangle object (derived/child class object) reference or pointer into a Shape object is called upcasting.

When the class inheritance diagram is drawn it is traditionally downwards. Casting from derived to base moves up the inheritance diagram -popularly known as upcasting.
Upcasting is always safe as we move towards a more generic type from a specific type. The downside of upcasting is that the more we go towards up, we lose the methods.

This is why the compiler allows us to do upcasting (without any explicit casts or other specific notation).To determine whether we should use composition or inheritance, we need to ask if we need to upcast from our new class to base class. If we must upcast, then inheritance is necessary.

while casting from float or double to an int value is always truncated. like 29.7 or 29.4 will always be 29.
double top=.9
double bottom=.1

int a =(int) top will always be 0 similarly int b=(int)bottom will always be 0
char c=(char)a+top will always be a and
char d=(char)b+top/bottom will be b

Type conversion rule:

Java follows a strict type conversion rules. They are as follows:


The below transformation is automatic and has no data loss involved:

See also  Class InterruptedIOException in Java
longfloat, double
Rule of thumb:

if the operand is two different types, they are automatically promoted to a higher type before any operation takes place.

  • If byte short and int variables are used in an expression, the result is always promoted to int to avoid overflow.
  • Similarly if long is used in an expression the whole expression is promoted to long
  • for float and double, the expression is promoted to the higher position-double.

In case if we are doing down casting then…

  • float to int truncates the fractional part
  • double to float causes rounding of digits
  • long to int causes dropping of excess higher-order bits.
When combining two different types of variables in an expression, it is always better to explicitly force conversion. It is safer than depending on java for automatic conversion.
Casting values:
Automatic casting is performed by java automatically. However, sometimes we want to force a type conversion little different way from automatic conversion. Like the ratio of female to male employees of an office. So if we say


since female and male both numbers are in integer, the automatic conversion will put the results into an integer. This will not reveal the actual numbers or the correct ratio will be lost as the decimal portion is ignored.
However, this issue can be resolved by locally converting one of the variables to the float


The (float) operator converts the female number to a floating-point for evaluation of the expression. Now due to the rule of automatic conversion, the expression is evaluated in floating-point mode, thus retain the fractional part of the result.

The process of such a local conversion is known as casting a value. The casting does not change the value of the variable. The generic casting rule:


for example:

float y=21.2f
int x=(int)(y+.5)

first, the expression is evaluated the right-hand side becomes 21.7f. But since we are casting it to int, the decimal value is truncated and x becomes 21.

Generic type casting:

Generics eliminates the need for explicit type casting in collections. A collection is a set of interfaces and classes that sort and manipulates a group of data into a single unit. To retrieve elements from a collection, we need to typecast the elements as each element in a collection is considered to an Object.

See also  Learn Methods in Java in a Quick Manner

Also, typecasting is an unsafe operation as the compiler can not check the wrong casts. The compiler throws an exception if the casts fail in run time. This is a very costly operation in the view of java development.

When using generics, the compiler inserts type casts at appropriate places to implement typecasting. Therefore typecast becomes implicit rather than explicit. Generics also determines the typecast error at compile time than run time. Collection can contain objects of one type.

Using generics, we can specify the type of information of data using a parameter. The type of information specifies the class and hierarchy of classes and interfaces to which the object belongs. The general syntax of generics as follows:

class MyClass{}

indicates that MyClass is a generic type.
an example:

public class ArrayListCollection{
    ArrayList<Interger> list=new ArrayList<Interger>();
    int total=0;
    Iterator<Intteger> iter=list.iterator();
        Interger val=iter.next();
    System.out.println("The total Amount is"+total);
    private static void NumberingList(ArrayList<Interger> list)
        list.add(new Integer(1));
        list.add(new Integer(2));

The process of assigning larger type data to smaller type data is called demotion or narrow conversion. This may result in a loss of information.

Share and Enjoy !

One thought on “What Is Casting Upcasting and Downcasting in Java?

  1. Do you mind if I quote a few of your articles as long as I provide credit and sources back
    to your weblog? My blog site is in the exact same area of interest as yours and
    my users would certainly benefit from some of the information you provide here.
    Please let me know if this ok with you. Regards!

Leave a Reply

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