- Java Type Casting
- Type Casting in Java – An Introduction
- Data Types in Java
- Primitive Data Type:
- Non-primitive Data Type:
- Date Types Flow chart:
- Typecasting
- 1) Widening Typecasting with Primitive data types
- 2) Widening Typecasting with Objects (Upcasting)
- 3) Narrowing Typecasting with primitive data types
- 4) Narrowing Typecasting with Objects (Downcasting)
- Conclusion
- Frequently Asked Questions
Java Type Casting
So, what do you do when you have to convert a data type into another data type when you are working on a piece of code? You guessed it right! There is a process of this kind of conversion, and it’s called casting. To make it easier for you, we will talk about the type of casting in Java in this blog. Below are the topics that you will go through.
Type Casting in Java – An Introduction
Java programming language consists of diverse features that are efficiently handled by numerous data types. Unfortunately, we are more often required to convert one type of data to another. Here, the concept of Type casting in Java comes into play.
Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting. Before diving into the typecasting process, let’s understand data types in Java.
Data Types in Java
Java is a statically typed language, i.e., variables must be declared before its use. Java has two major categories of data:
Primitive Data Type:
It is the most fundamental data type. Java consists of 8 primitive data types:-
Boolean: It is used to store two types of values, i.e., true or false. This data type is commonly used as a flag in code logic. The default value of the Boolean data type is false.
Byte: It can store 8-bit signed two’s complement integer. The default value of a byte data type is 0. The range lies between -128 to 127
Char: This data type is used to store a single 16-bit Unicode character. It stores just one character in simple words, and the word Unicode is used because java uses the Unicode system, not the ASCII system. The size of this data type is 16bits (2 bytes). It is declared like below:
Int: It is a data type that stores 32-bit (4 bytes) two’s complement integer, i.e., its range lies within (-2^31 to 2^32 – 1). It is declared using the int keyword followed by the name of the variable.
Short: Similar to ‘int,’ short is also used to store integer values but within 16-bit (2 bytes) signed two’s complement. Its range lies within (-2^15 to 2^16-1). It is declared using the short keyword.
Long: It is 64 bit two’s complement integer and its range lies within (-2^63 to2^64 – 1) i.e. ( -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808). It is declared using the long keyword.
Float: As the name indicates, it is a data type that holds data with more precision, i.e., floating-point numbers. It is a single-precision 32-bit (4 bytes) IEEE754 floating-point. It is declared using the float keyword.
float decimalNum = 8.213245f
Double: It is a double-precision 64-bit (8 bytes) IEEE754 floating point. It is declared using the double keyword.
Non-primitive Data Type:
Unlike primitive data types, which don’t have any associated methods with them, non-primitive data types have associated methods. It refers to the Objects. It is also called Object data types or Reference Data Types. Example:
String: It is a sequence of characters.
Example: String str = “Hello World!!” ;
Array: Collection of similar types of elements.
Example: String[] technology = [‘Java’ , ‘C’ , ‘Python’]
Other examples of non-primitive data types are Class, Objects, and Interface.
Date Types Flow chart:
Typecasting
As explained initially, typecasting is nothing but a way of changing the data type of a variable or an object from one form to another. Every programming language has its own rules and ways of type conversion. For example, an integer value can be converted to a floating-point value or a String, i.e., from numeric to textual representation.
Typecasting in java programming is grouped into several broad categories:
1) Widening Typecasting with Primitive data types
The process of conversion of a lower data type to a higher data type is known as Widening Typecasting. Java automatically performs this type of casting without any explicit code writing, which is why this type of casting is also known as Automatic typecasting.
- Important Note: During this conversion, no information is lost on the overall magnitude of the numeric value.
To perform this conversion, two data types are supposed to be compatible with each other. 19 types of primitive conversion are possible in widening type casting:
a.) byte to short, byte to int, byte to long, byte to float, byte to double
byte b = 2; short s = b; int i = b; long 1 = b; float f = b; double d = b;
b.) short to int, short to long, short to float, short to double
short s = 3; int i=s; long 1 = s; float f = s; double d = s;
c.) char to int, char to long, char to float, char to double
char c = ‘d’ ; int i = c ; long l = c; float f = c; double d = c;
d.) int to long, int to float, int to double
int i = 32 ; long l = i; float f = i; double d = i;
e.) long to float, long to double
long l = 78; float f = l; double d = l;
f.) float to double
float decNum = 23.45f ; double d = decNum;
Widening Type casting example in IDE:
Examples of Widening Type casting…!!
byte to short: 5
byte to int: 5
byte to long: 5
byte to float: 5.0
byte to double: 5.0
Fig: Widening Type Conversion flow
2) Widening Typecasting with Objects (Upcasting)
Objects of a class can be cast into objects of another class if both classes are related to each other through the property of inheritance, i.e., one class is the parent class, and the other class is the child class.
This type of casting superclass object (parent class) will hold the sub-class object’s properties.
Let’s understand widening casting with objects using an example:
class Animal < protected String name; protected int age; public Animal(String name, int age)< this.name = name; this.age = age; >public void animalInfo() < System.out.printIn("Animal class info: "); System.out.printIn("Name: "+this.name); System.out.printIn("Age: "+this.age); >> public class Dog extends Animal < public String color; public Dog(String name, int age, String color)< super(name, age); this.color = color; >public void dogInfo() < System.out.printIn("Dog class: "); System.out.printIn("Name: "+this.name); System.out.printIn("Age: "+this.age); System.out.printIn("Color: "+this.color); >public static void main(String[] args) < Dog dog = new Dog("Leo", 2, "Brown"); Animal animal = new Animal("Casper", 3); animal = dog; //implicit casting Object of dog to Animal animal.animalInfo(); >>
Animal class info:
Name: Leo
Age: 2
In the above code, the Animal class is called the parent class, and the Dog class is called the child class because the Dog class extends the Animal class, and the Dog class has acquired all the properties of the Animal class:
- In the main() method, first, we have created an object of the Dog class using a new keyword, followed by the creation of the Animal class Object.
- In the second step, we have simply assigned the reference object of the Dog class to the animal class, i.e., animal = dog; this type of casting is known as implicit casting or widening or upcasting of objects.
- Widening takes place when a subclass object reference is assigned to a wider superclass object. Like, in the above example dog object was assigned to the Animal object.
3) Narrowing Typecasting with primitive data types
The process of conversion of higher data type to lower data type is known as narrowing typecasting. It is not done automatically by Java but needs to be explicitly done by the programmer, which is why it is also called explicit typecasting.
22 types of primitive conversion are possible in narrowing type casting:
a.) short to byte, short to char
short input = 65 ; byte b = (byte) input ; char c = (char) input ; //
b.) char to byte, char to short
char input = 65 ; byte b = (byte) input ; short s = (short) input ;
c.) int to byte, int to short, int to char
int input = 12 ; byte b = (byte) input ; short s = (short) input ; char c = (char) input
d.) long to byte, long to short, long to char, long to int
long input = 12 ; byte b = (byte) input ; short s = (short) input ; char c = (char) input ; int i = (int) input ;
e.) float to byte, float to short, float to char, float to int, float to long
float input = 12.0f ; byte b = (byte) input ; short s = (short) input ; char c = (char) input ; int i = (int) input ;
f.) double to byte, double to short, double to char, double to int, double to long, double to float
double input = 65.25 ; byte b = (byte) input ; short s = (short) input ; char c = (char) input ; int i = (int) input ; long l = (long) input ; float f = (float) input ;
Narrowing Type casting example in IDE:
Examples of Narrowing primitive Type casting…!!
float to short: 65
float to byte: 65
float to char: A
float to int: 65
Fig: Narrowing Type casting conversion flow
4) Narrowing Typecasting with Objects (Downcasting)
Similar to widening typecasting, the object of one class can be narrowed cast into the object of another class when two classes hold the relationship of parent class and child class through inheritance. The class that inherits the properties of another class is called a child class or sub-class, while the inherited class is called a Parent class or superclass.
But unlike widening typecasting, the programmer must explicitly use a cast operator to perform narrowcast. If we do not perform narrowcasting, the java compiler will throw a “compile-time error”.
Let’s understand Narrowing type casting with an example:
class Animal < protected String name; protected int age; public Animal(String name, int age)< this.name = name; this.age = age; >public void animalInfo() < System.out.printIn("Animal class info: "); System.out.printIn("Name: "+this.name); System.out.printIn("Age: "+this.age); >> public class Dog extends Animal < public String color; public Dog(String name, int age, String color)< super(name, age); this.color = color; >public void dogInfo() < System.out.printIn("Dog class: "); System.out.printIn("Name: "+this.name); System.out.printIn("Age: "+this.age); System.out.printIn("Color: "+this.color); >public static void main(String[] args) < Animal animal = new Dog("Leo", 2, "Black"); Dog dog = (Dog) animal; //implicit casting Object of student to person dog.animalInfo(); dog.dogInfo(); >>
Animal class info:
Name: Leo
Age: 2
Dog class:
Name: Leo
Age: 2
Color: Black
In the above code, the Animal class is the parent class, and the Dog class is the child class because the Dog class extends the Animal class, and the Dog class has acquired all the properties of the Animal class:
- In the main() method, first, we have created an object of the Dog class using the reference of the parent class, i.e., Animal animal = new Dog(“Leo”, 2, “Black”); otherwise, we’ll encounter a runtime exception.
- In the second step, we have simply assigned the reference object of the Dog class to the animal class, i.e., Dog dog = (Dog) animal; this type of casting is known as explicit casting or narrowing or down-casting of objects.
- Narrowing typecasting occurs when a superclass object reference is narrow-casted and assigned to a narrower sub-class object. Like, in the above example, an animal object was assigned to a Dog object reference.
Conclusion
In this article, we studied data types in java and their syntax and characteristics, which helped build the foundational understanding of Type casting in Java. You can also take up a Free java course to help you understand more about the concepts.
We also discussed widening or implicit type casting with primitive data types and reference objects and narrowing or explicit typecasting, which needs to be explicitly programmed with primitive data types and reference objects as well.
We also explored type casting with various hands-on examples. Please feel free to explore more examples on your own to get a better understanding of the concept.
Great Learning has collaborated with IIT Roorkee to offer an Advanced Certificate program in Full Stack Software Development. Do check out this program to ace your career and become a certified full-stack developer today.
Also, if you are preparing for Interviews, check out these OOPS Interview questions to ace it like a pro.
Frequently Asked Questions
An object can be converted from one data type to another using typecasting, also known as type conversion. It is employed in the programming language to guarantee that a function processes variables appropriately. Converting an integer to a string is an example of typecasting.
There are primarily two types of casting, namely, widening type casting and narrowing type casting.
Data can be type cast to be transformed from one data type to another. Type conversion or type coercion are other names for this data conversion procedure. Both reference and primitive data types can be cast in Java. Data cannot be modified with casting; only the data type can be altered.
Type casting is a process by which a developer transforms one data type into another data type using the casting () operator. When compiling a program or piece of code, type conversion enables a compiler to transform one data type into another. Both compatible and incompatible data types can be utilized with it.
In a programming language, it is used to guarantee that a function processes the variables properly. The conversion of an integer into a string is an example of typecasting. If one of the numbers is saved as a string and the other as an integer, this might be used to contrast the two values.
Great Learning’s Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You’ll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.