When a value of one type is assigned
to another is known as type casting. Primitive
data types occupy different sizes in the memory. Such as, an integer is 32 bit
and long is 64 but. For passing the values between different data types we need
type casting.
There
are two type of casting
1.
Implicit or Upcasting
2.
Explicit or Downcasting
Implicit
type casting possible when both types are compatible and the destination type
is larger than the source.
In
Explicit conversion never take place automatically. Converting a double or long
to an int is not possible because it requires more storage space. For a
conversion we use an explicit conversion.
Example-1
:
//between
primitive data type
public class TypeCast
{
public static void main(String
args[])
{
//Implicit Type Casting or
Downcasting
int a=10;
long b=a;
double d=a;
System.out.println("\nInteger a ="+a+" Long b=
"+b+" Double d= "+d);
//Explicit Type Casting or
Upcasting
d=12.55;
b=1234;
a=(int)b;
System.out.println("\nLong b= "+b+ " Integer a
="+a);
a=(int)d;
System.out.println("\nDouble
d= "+d+ " Integer a ="+a);
}
}
Example-2
:
//between
Objects
//Object
Type Casting
class Object
{
void main()
{
//Object Type Casting
System.out.println("Test");
}
}
public class Object1 extends Object
{
public static void main(String
args[])
{
Object O1=new Object();
Object1 O2=new Object1();
O1=O2;
}
}
No comments:
Post a Comment