Вы находитесь на странице: 1из 4

JAVA PROGRAMMING

(DCO-515)

Program 2: Write a program in java for widening and narrowing conversion.

Submitted by:
Mohd Aadil Rana
Roll. No. 16-DCS-031
Diploma in Computer Engineering- V Semester

Computer Engineering Section


University Polytechnic, Faculty of Engineering and Technology
Jamia Millia Islamia (A Central University)
New Delhi-110025
Session 2018-2019
Type conversion in Java

When you assign value of one data type to another, the two types might not be compatible
with each other. If the data types are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion and if not then they need to be casted or
converted explicitly. For example, assigning an int value to a long variable.
Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This
happens when:
● The two data types are compatible.
● When we assign value of a smaller data type to a bigger data type.
For Example, in java the numeric data types are compatible with each other but no
automatic conversion is supported from numeric type to char or boolean. Also, char and
boolean are not compatible with each other.

Narrowing or Explicit Conversion


If we want to assign a value of larger data type to a smaller data type we perform explicit
type casting or narrowing.
● This is useful for incompatible data types where automatic conversion cannot be done.
● Here, target-type specifies the desired type to convert the specified value to.
# Source Code
class Conversion

public static void main(String [] args)

byte a=10;

short b=125;

int c=300;

float d=2.15f;

double e=3.13473837342843823743;

//WIDENING CONVERSION

short f=a; //byte convert to short

int g=b; //short convert to integer

float h=c; //integer convert to float

double i=d; //float convert to double

//NARROWING CONVERSION

byte j=(byte)a; //short convert to byte

short k=(short)c; //integer convert to short

int l=(int)d; //float convert to integer

float m=(float)e; //double coonvert to float

System.out.println("WIDENING CONVERSION");

System.out.println("Byte value is: "+a+"\nAfter conversion to Short: "+f);

System.out.println("Short value is: "+b+"\nAfter conversion to Integer: "+g);

System.out.println("Integer value is: "+c+"\nAfter conversion to float: "+h);

System.out.println("Float value is: "+d+"\nAfter conversion to Double: "+i);


System.out.println("NARROWING CONVERSION");

System.out.println("Short value is: "+b+"\nAfter conversion to Byte: "+j);

System.out.println("Intger value is: "+c+"\nAfter conversion to Short: "+k);

System.out.println("float value is: "+d+"\nAfter conversion to Integer: "+l);

System.out.println("Double value is: "+e+"\nAfter conversion to Float: "+m);

//Output

Вам также может понравиться