Web Tutor

Other Entries

Type Casting In Java

Type casting is a way of converting data from one data type to another. This process of data conversion is also known as type conversion or type coercion.
Type casting in java are grouped into several broad categories.
Widening Typecasting with primitive data types
The process of conversion of a lower data type to a higher data type is also known as widening typecasting. Java automatically performs this type of casting without any explicit code writing, which is why this type of casting is also known as automatic casting.
Note that during this conversion, no information is lost on the overall magnitude of the numeric value.
To perform this conversion, two data types are supposed to be compatible with each other. 19 types of primitive conversion are possible in widening type casting.
a.)byte to short, byte to int, byte to long, byte to float, byte to double
byte b = 2;
short s = b;
int i = b;
long l = b;
float f = b;
double d = b;
b.) short to int, short to long, short to float, short to double
short s = 3;
int i = s;
long l = s;
float f = s;
double d = s;
c.)char to int, char to long, char to float, char to double
char c = 'd';
int i = c;
long l = c;
float f = c;
double d = c;

d.)int to long, int to float, int to double

int i = 32;
long l = i;
float f = i;
double d = i;

e.)long to float, long to double

long l = 78;
float f = l;
double d = l;

f.)float to double

float decNum = 23.45f;
double d = decNum;



package HelloWorld;

/*This program demonstrates type casting in java
 * as a data type

public class HelloWorld {
	public static void main(String[] args) {
		byte b = 5;
		short s = b;
		int i = b;
		long l = b;
		float f = b;
		double d = b;
		System.out.println("byte to short: "+s);
		System.out.println("byte to int: "+i);
		System.out.println("byte to long: "+l);
		System.out.println("byte to float: "+f);
		System.out.println("byte to double: "+d);





Posted in Java on September 11 2022 at 08:33 AM

Comments (0)

No login

Popular Blogs