Step 10:Type Casting, Boxing/InBoxing and OutBoxing -6th hour +code

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
int a1=20; //from int
double b=a1; //to double
System.out.println(b);

//downcasting
double x=10.0d; //from double
int c=(int)x; //to int
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);
}
}

2 comments

Leave a Reply to Core Java in 25 hours Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.