Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconWhat is Type Casting in Java | Understanding Type Casting As a Beginner

What is Type Casting in Java | Understanding Type Casting As a Beginner

Last updated:
27th Mar, 2020
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
What is Type Casting in Java | Understanding Type Casting As a Beginner

Programming is a set of instructions, in a special language, given to the computer to perform a set of tasks. Though many people are using the languages for professional purposes, some developers see it as a way of playing with data and creating functions, solutions, and analysis; they never thought possible.

Students of science are well aware that there are different programming languages, and one of the most prominent ones in Java. No computer engineering student can remain distant from this language. More importantly, professionals can study programming language independently. 

Interestingly, Java is a programming language that has several data types to challenge and interest the developers. However, familiarity with the data types is important to play with the data and create instructions as per the end-objective. At the time of coding, a developer may need to change the data types to know how the variable works within the code – this testing of the data variable is known as Type Casting.

Check out our free courses to get an edge over the competition.

Ads of upGrad blog

In simpler words, computer programmers change one data type to another data type so that a function correctly processes a variable. Typical examples would include converting a floating-point number to an integer, or an integer to a string. 

Enroll in Software Engineering Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Understanding Type Casting in Java

Now, that the mechanics of typecasting are clear, it is time to shift attention to type casting in Java. 

Typecasting, or type conversion, is the process of assigning a primitive data type’s value to another primitive data type. Programmers need to check the compatibility of the data type they are assigning to another data type, in advance. Typecasting is automatically performed if compatibility between the two data types exists. This type of conversion is called automatic type conversion. On the other hand, in the absence of compatibility between the two data types, then the conversion or casting takes place explicitly. 

Explore Our Software Development Free Courses

Check out upGrad’s Advanced Certification in Cloud Computing

Typecasting in Java is also the casting of a class or interface into another class or interface. Java supports both polymorphism and inheritance as it is an object-oriented programming language. There could be instances when a SubClass object is pointed as a SuperClass reference variable. However, a Java compiler won’t know this. So, calling a method that has been declared in the SubClass is useless. To make it a useful exercise, you need to first cast that a SubClass object into the type it originally existed as. This is a great example of how type casting in Java works. 

Read: Future Scope of Full Stack Developers

Knowing typecasting is not enough as it is equally important to be well aware of the Java rules that need to be followed. One such rule says that interfaces or classes belonging to a single type hierarchy can be converted or cast into one another. If objects without the same type hierarchy or parent-child relationship are converted, a compile-time error to be displayed on your screen.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

Let’s look at another scenario you can face as a developer when choosing two objects that belong to the same type hierarchy. But, if the type of the object you are casting and the type of object you are casting it on are not the same, then you will get a ClassCastException. 

The most surprising thing is that many developers and programmers are unaware of the importance of typecasting. Typecasting provides access to methods and fields that the target class or type is declared on. There is no other way to access these.

Explore our Popular Software Engineering Courses

Now, let us look at the different type conversion or casting in Java

There are two types of conversion or casting, namely primitive type casting and reference typecasting. 

Types of Casting in Java

Primitive type casting

It allows the developer to cast the value of one primitive into another. The seven primitive data type values are Boolean, Byte, Char, Short, Int, Long, Float and Double. There are two sub-types of primitive type casting:

1. Widening casting or implicit conversion:

Widening casting involves the casting of a data type with a lower value into a data type with a higher value (Widening data type) without any loss of information. It is a big risk in the precision of the casting when considering a wider conversion between different numeric data types. Loss of small bits of information or value is possible. 

In-Demand Software Development Skills

Also read: Full Stack Project Ideas and Topics

2. Narrowing casting or explicit conversion:

It is the opposite of widening casting. It involves the casting of a data type with a higher value into a data type with a lower value (Narrower data type). If not handled carefully, it can lead to loss of information.  

An implicit conversion doesn’t require the developer to provide inputs and is performed automatically. On the other hand, an explicit conversion is performed by the developer alone. 

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Reference type casting

If two different types of classes are associated with each other by inheritance and one of those classes is the SubClass of another, then these classes can undergo casting. It is important to ensure that the casting is in line with run-time rules as well as compile-time rules in Java. Reference type casting is further divided into two types:

Read our Popular Articles related to Software Development

1. Upcasting:

Upcasing involves the conversion of an object of SubType into an object of SuperType. Java has the provision for assigning the object without requiring the addition of an explicit cast. The compiler would know what is being done and would cast the SubType value to SuperType. This way, the object is brought to a basic level. Developers can add an explicit cast without worrying about any issues. 

2. Downcasting:

Ads of upGrad blog

Downcasting involves the conversion of a SuperType object into a Subtype object. It is the most frequently used casting wherein it is communicated to the compiler that the value of the base object isn’t it’s own but of the SuperType object. 

Wrapping up

To sign off, learning Java typecasting is necessary for becoming a successful developer or programmer. The intent is to define functions and then ensure variables within the communication are performing as per the end-functionality. Knowing and mastering the different types of casting methodologies goes a long way in helping the programmer deliver the most complex functionalities. In direct words, it is a basic which big businesses and brands to improve their end-user engagement.

If you’re interested to learn more about full stack development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Arjun Mathur

Blog Author
Arjun is Program marketing manager at UpGrad for the Software development program. Prior to UpGrad, he was a part of the French ride-sharing unicorn "BlaBlaCar" in India. He is a B.Tech in Computers Science from IIT Delhi and loves writing about technology.

Frequently Asked Questions (FAQs)

1Why is Java popular?

Java's WORA philosophy, which is to Write Once Run Anywhere, makes it a popular language. You can write code whenever and wherever you want and run it on any system or anyplace you choose. This is what most appeals to programmers. Java programs can run on a variety of computers that have the Java Runtime Environment (JRE). JRE is compatible with a wide range of platforms, including mobile phones, Windows, PCs, and Linux. Java is a programming language that is used to create web applications. It's also commonly utilized in the development of Android apps. Java is also an excellent option for scientists who want to develop scientific apps. It's also used in software development and game development.

2What makes Java a secure programming language?

Due to a number of features, Java is a very secure language. Since Java does byte-code verification prior to execution, it is impossible for the program to jump to a malicious or undefined instruction or commit a typing mistake at the instruction level. The program is free of type errors thanks to the automated bounds checking of arrays, null checking of references, and casts verification. Run-time security checks are performed whenever a new code is loaded. By mediating access to system resources and prohibiting the application from loading or creating any arbitrary code at run-time, the Java run-time makes it easy for the Java run-time to avoid any arbitrary code from executing. Java ensures the security of libraries.

3Where is Java used?

Java can be found everywhere, from desktop computers to mobile phones. Java is used by a wide range of sectors and businesses to meet their technical needs. It's utilized in the financial industry, for example, to handle transactions. Because it is being used in information technology to manage implementation requirements, the IT industry employs the majority of Java developers. Companies utilize it in the stock market since there are algorithms that help them locate the stocks they should invest in. As a result, Java is not restricted to a single area. Many major corporations, like Google, Accenture, Uber, Philips, CapitalOne, and others, make use of it.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 7 Node js Project Ideas & Topics
31536
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46896
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers & Experienced]
901296
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners & Experienced]
51950
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers & Experienced]
909101
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34710
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers & Experienced]
902362
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26105
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions & Answers [2024]
4314
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon