PRIMITIVE TYPE CAST

Casting lets you convert primitive values from one type to another.
Casts can be implicit or explicit.
IMPLICIT CAST:
An implicit cast means you don't have to write code for the cast; the conversion happens automatically.
Typically, an implicit cast happens when you're doing a widening conversion. In other words, putting a smaller thing (say, a int) into a bigger container (like an double).
example:
class demo
{
public static void main(String[] args){
int a=1;
int b=1;
double c=a+b;
System.out.println(c);
}
};

EXPLICIT CONVERTION:
What happens we tried to put a larger thing (say, a double) into a smaller container (like a int).You will get "possible loss of precision" compiler errors this time.
In this case we need to type cast explicitly.
EXAMPLE:
class demo
{
public static void main(String[] args){
double a=1;
double b=1;
int c=(int)(a+b);//explicit type cast
System.out.println(c);
}
};

IF we are calculating two different values of different type, then we need the greater container to store the result. Otherwise explicit type cats is needed.
short a=2; long b=4;
long c=a+b;//implecit type cast
long c=(long)(a+b)//explicit type cast(otherwise error)

No comments:

Post a Comment