Converting a value of one data type into a variable of another data type is called as type casting.
Type casting is called as type conversion.
Types
Type casting is of two types they are
Types
Type casting is of two types they are
1)Implicit type
Casting (Widening)
2)Explicit type Casting (Narrowing)
2)Explicit type Casting (Narrowing)
Widening or Implicit type Casting
Conversion of smaller data type into larger data type is called as Widening
or Implicit Casting
It is called as Automatic type conversion
There is no data
loss in implicit type casting
e.g
int a=100 ;
double b;
b=a;
double b;
b=a;
Example :
public class Demo
{
public static void main(String[] args)
{
int a = 100;
double b;
b=a;
System.out.println("Int value is:
"+a);
System.out.println("Double value is:
"+b);
}
}
Output:
Int value is: 100
Double value is: 100.0
Note:
Here we are converting int to double that means smaller data type to bigger data type. So there is no data loss occurs.
Narrowing or Explicit type Casting
Conversion of larger datatype into
smaller data type is called as Narrowing or Explicit type conversion
It is not Automatic type conversion because you have to do explicitly.
Data loss occurs in explicit type casting because it is the conversion of
larger datatype into smaller data type.
e.g:
double a=23.456;
int b;
b=(int)a;
Example :
public class Demo
{
public static void main(String[] args)
{
double a=23.456;
int b;
b=(int)a;
System.out.println("Double value is: "+a);
System.out.println("Int value is: "+b);
}
}
Output
Double value is:23.456
Int value is:23
Output
Double value is:23.456
Int value is:23
Note:
Here we are converting double to int that means bigger data type to
smaller data type.So data loss occurs.
No comments:
Post a Comment