CLASS - X (ICSE)
COMPUTER APPLICATION
Type Conversion
®
When
different types of variables and constants are mixed up in an expression, they
are converted in one common type implicitly by the compiler. This is called
type conversion.
®
Java
facilitates the type conversion in two forms:
Implicit
type conversion:-
®
An
implicit type conversion is a conversion performed by the compiler without
programmer’s intervention.
®
The
java compiler converts all operands upto the data type of the largest data
type’s operand, which is called type
promotion.
®
Example:
int a=10;
float f=a;
®
Program
class ExampleOfImplicit{
public static void main(String args[]){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0
Explicit
type conversion :-
®
An
explicit type conversion is user-defined that forces an expression to be of
specific data type.
®
It
is also known as type casting.
®
Example:float
x=3.4f;
int
y=(int)x;
®
Program
class ExampleOfExplicit{
public static void main(String args[]){
float f=10.5f;
int a=(int)f;
//int
a=f; (compile time error)
System.out.println(f);
System.out.println(a);
}
}
Output:
10.5
10
®
If
you will do typecast then it means you are doing forcefully as you can see int
y=(int)x; here data is lost but no error.
®
Always
remember you can do typecast but java usually don’t allow it by itself.
Conversions that compiler do itself (implicit conversions)






No comments:
Post a Comment