Explicit Type Conversion Example in Java

Write a program to perform explicit type conversion. Where implicit conversion is not possible.

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

public class Hello { public static void main(String args[]) { //Write your code here } }

Program or Solution

				
				
					

class Program


{


public static void main(String args[])


{


byte b = 10;

char ch = 'C';

short num = 500;

int i = 5000000;


//during explicit conversion there will be loss in data 

//for example 5000000 cannot accommodate in byte because the size is 1 byte (256 combinations only possible).

// in this case 5000000 will be divided by 256 and remainder will be stored in byte (so 64)

b=(byte)i;

System.out.println(b);

ch =(char)i;

System.out.println(ch);

b = (byte) num;

System.out.println(b);

num = (short)i;

System.out.println(num);


}


}


Output

Explicit Type Conversion Example in Java Output

Program Explanation

When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.

During explicit conversion there will be loss in data. for example, 5000000 cannot accommodate in byte because the size is 1 byte (256 combinations only possible). In this case 5000000 will be divided by 256 and remainder will be stored in byte (so 64 us stored in b)

Comments