Definitions

-Assigning a value of one type to a variable of another type is known as Type Casting.

Datatype hierarchy-
(Biggest datatype) double > float > long > int > char > short > byte (smallest datatype)

primitives
type-casting-different-forms
(i)Widening/Automatic type conversion/Up casting
-When value of small datatype is saved into big datatype.
i.e-
int i=10;
double d=i;

(ii)Narrowing/manual type conversion/down casting
-When value of big datatype is saved into small datatype.
i.e- double d=455.3d;
int i=(int)d;

Code samples are here

1-Program to perform upcasting and downcasting


package typecasting6;
public class Typscting {

public static void main(String[] args) {
//upcasting
Integer a1=20; //from non primitive(a1)
int b=a1; //to primitive(b)
System.out.println(b);

//downcasting
int x=10; //from primitive(x)
Integer c=x; //to non primitive(b)
System.out.println(c);
}
}

Boxing/InBoxing and OutBoxing-
(i) Boxing/InBoxing
– Conversion of primitive into non primitive
i.e – int i=10;
Integer i1=i; // Integer is a class so i1 is a object(non primitive)

(ii) OutBoxing
– Conversion of non primitive into primitive
i.e Integer i=10;
int i1=i;

autoboxing-and-unboxing-in-java

code samples are here

2-Program to perform boxing and outboxing


package boxingNunboxing7;
public class BoxngUnboxing {

public static void main(String[] args) {

//boxing
int x=10; //from primitive(x)
Integer c=x; //to non primitive(b)
System.out.println(c);

//out boxing
Integer a1=20; //from non primitive(a1)
int b=a1; //to primitive(b)
System.out.println(b);
}
}

Advertisements