Type Casting in Java
Type conversion or type casting simply means different ways
of changing an entity of one data type into another data type. e.g. simply
conversion of integer value into floating value or text.
Java supports two types of casting :
1.) Primitive data type casting
2.) Reference data type casting
Note : we will discussed Reference data type casting in next
discussion.
Primitive data type casting :
Primitive data types
are basic data types of any programming language we can also say that these
are building blocks of any programming
language.
In Java Primitive data types are classified into eight
different types :
1. Boolean Data type : which contains its value
either true or false.
2 2. Char : character data type whose values are 16
bit Unicode character
3. Arithmetic Data type : which also categorized
into two different ways :
- Integral types :
- Byte
- Int
- Long
- Short
- Floating–point types
- Float
- Double
- Implicit Type casting
- Explicit type casting :
Implicit Type casting : Implicit type casting is done
automatically by compiler.In case of Implicit type casting Programmers do not apply any effort for it.
What is implicit Type casting ?
To understand Implicit Type casting in more detail we took
an example :
Suppose I am taking a variable as int and assigning its value
is ‘a’ which is char value
Int x=’a’;
public class ImplicitExample {
public static void
main(String a[]){
int x ='a';
System.out.println(a);
}
}
After adding this code inside Java code editor of its
execution
And after compiling this code we obtain this result
And after compiling this code we obtain this result
Some Important points
regarding Implicit type casting
- Bigger Data type variable stores smaller data type value
- Compiler is responsible for implicit type casting
- In case of Implicit type casting we stores small value into big container and this process is known as widening or Upcasting.
Explicit
Type Casting :
Explicit type casting is done by programmer because in this
programmer wants to store bigger data type value into smaller data type
variable which is practically not possible and so compiler neglect for doing
this and shows compile time error but if Programmer wants to compile this
program on any cost then in that case java provides facility of type casting
i.e Explicit Type casting.
Comments
Post a Comment