Typecasting
- Converting one type to another type is called typecasting.
- Conversion is done from primitive to primitive or nonprimitive to nonprimitive.
Example
int i = 10;
double d = (double) i;
SOP(i);
SOP(d);
int j = (int) 102.56;
SOP(j);
- Boolean type can't be casted.
- If we convert smaller to bigger type, it is called widening or explicit type casting.
- If we convert bigger to a smaller type, it is called narrowing or implicit type casting.
- Widening is implicit or automatic.
- Narrowing is explicit.
- In widening there is no loss of data.
- In narrowing, loss of data or loss of precision may take place.
8 primitive types, their size and default values
Type | Size | Default value |
byte | 1 byte | 0 |
short | 2 byte | 0 |
int | 4 byte | 0 |
long | 8 byte | 0 |
float | 4 byte | 0.0f |
double | 8 bye | 0.0d |
char | 2 byte | '\u0000' |
boolean | Not defined | false |
public static void main(String[] arg){
m1('a');
m1(34.562);
}
static void m1(int a){
System.out.print(a);
}
class J{
public static void main(String[] arg){
m1(10);
m1('a');
m1(23.45);
}
static void m1(int a){
System.out.print("m1(int a)");
}
static void m1(double d){
System.out.print("m1() double");
}
}
static double m1(){
return 'a';
}
In the above example, return type is double, but we are using char as a return type. It is possible because of auto widening. Smaller type is a covariant return type for a bigger type.
Comments
Post a Comment