Core Java - Type Casting

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); // 10
SOP(d); // 10.0
int j = (int) 102.56;
SOP(j); // 102
  • 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
TypeSizeDefault value
byte1 byte0
short2 byte0
int4 byte0
long8 byte0
float4 byte0.0f
double8 bye0.0d
char2 byte'\u0000'
booleanNot definedfalse
public static void main(String[] arg){
m1('a');
m1(34.562); // compile time error
}
static void m1(int a){
System.out.print(a);
}

class J{
public static void main(String[] arg){
m1(10); // calls int
m1('a'); // calls int
m1(23.45); // calls double
}
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

Popular posts from this blog

Java Variables and Datatype

JAVA Features

Java Fundamentals