What Is Casting Upcasting and Downcasting in Java?

Spread the love
  • 2

The relationship between base class and 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(up casting) 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 loosing 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 to cast primitive to another except boolean. Class type do 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 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 -calculateArea() so as the child class-Rectangle.createShape() method accepts an Shape reference.In Rectangle class the main method call createShape by providing Rectangle object.
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 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 an Shape object is called upcasting.
When 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 to more generic type from specific type.The downside of upcasting is that the more we go towards up,we loose the methods.This is why 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 values are 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:

char char byte short int long float double
byte int int int int long float double
short int int int int long float double
int int int int int long float double
long long long long long long float double
float float float float float float float double
double double double double double double double double

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

From To
byte Short,char,int,long,float,double
short int,long,float,double
char int,long,float,double
int long,float,double
long float,double
float double
Rule of thumb:

if the operand are two different types,they are automatically promoted to 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 avid overflow.
  • Similarly if long is used in a 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 trancate 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 more 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 resultant into integer. This will not reveal the actual numbers or the correct ratio will be lost as decimal portion is ignored.
However this issue can be resolved by locally converting one of the variable to the float


The (float) operator converts the female number to floating point for the purpose of evaluation of the expression.Now due to 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 of explicit type casting in collections.A collection is a set of interfaces and classes that sort and manipulate a group of data into 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.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 type casting.Therefore typecast becomes implicit rather than explicit.Generics also determines the typecast error error at compile time than run time.Collection can contain objects of one type. Using generics ,we can specify the type information of a data using a parameter.The type 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 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 loss of information.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 2


Please enter your comment!
Please enter your name here