Veena Antony Asst - Professor Bca Ct&Ism ST - Teresa's College (Autonomous)
Veena Antony Asst - Professor Bca Ct&Ism ST - Teresa's College (Autonomous)
Veena Antony Asst - Professor Bca Ct&Ism ST - Teresa's College (Autonomous)
Asst.Professor
BCA CT&ISM
St.Teresa’s College(Autonomous)
TYPE CASTING
2
• When you assign value of one data type to
another, the two types might not be
compatible with each other. If the data types
are compatible, then Java will perform the
conversion automatically known as Automatic
Type Conversion and if not then they need to
be casted or converted explicitly. For example,
assigning an int value to a long variable.
3
Widening or Automatic Type Conversion
Widening conversion takes place when two data types are
automatically converted.
This happens when:
• The two data types are compatible.
• When we assign value of a smaller data type to a bigger data
type.
• For Example, in java the numeric data types are compatible
with each other but no automatic conversion is supported
from numeric type to char or boolean. Also, char and boolean
are not compatible with each other.
4
class Test
{
public static void main(String[] args)
{
int i = 100; // automatic type conversion
long l = i; // automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l); Output:
Int value 100
System.out.println("Float value "+f); Long value 100
Float value 100.0
}
}
5
Narrowing or Explicit Conversion
• If we want to assign a value of larger data type to a
smaller data type we perform explicit type casting or
narrowing. This is useful for incompatible data types
where automatic conversion cannot be done.
• Here, target-type specifies the desired type to
convert the specified value to.
• char and number are not compatible with each
other.
6
//Java program to illustrate //Java program to illustrate explicit type
incompatible data conversion
public class Test
// type for explicit type conversion
{
public static void main(String[] args)
{
double d = 100.04;
public class Test long l = (long)d; //explicit type
casting
{
int i = (int)l; //explicit type casting
public static void main(String[]
System.out.println("Double value
args) "+d);
{ //fractional part lost
char ch = 'c'; System.out.println("Long value "+l);
Output: //fractional part lost
int num
7: error: = 88;
incompatible types: Output:
System.out.println("Int
Double value 100.04value "+i);
ch = num;
possible lossy conversion from
} Long value 100
}int to char ch = num; }
^ Int value 100
} 1 error
7
THANK YOU!!