Assigning a value of one type to a variable of another type is known as Type Casting.
In Java, type casting is classified into two types,
1.Implicit casting
2.Explicit casting
1. Implicit casting (widening conversion)
//programming789.blogspot.com/
public class CastExample
{
public static void main(String[] args)
{
int i = 102;
long l = i; //Implicit type casting
double d = l; //Implicit type casting
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Double value "+d);
}
}
Int value 102
Long value 102
Double value 102.0
2.Explicit casting(narrowing conversion)
When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.
Example:
/*explicit type casting program in java.*/
//programming789.blogspot.com/
public class CastExample
{
public static void main(String[] args)
{
double d = 102.04;
long l = (long)d; //explicit type casting
int i = (int)l; //explicit type casting
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Long value 102
Int value 102
In Java, type casting is classified into two types,
1.Implicit casting
2.Explicit casting
1. Implicit casting (widening conversion)
A data type of lower size is assigned to a data type of higher size. This is done implicitly by the JVM. The lower size is widened to higher size.
Example:
/*Implicit type casting program in java.*/ //programming789.blogspot.com/
public class CastExample
{
public static void main(String[] args)
{
int i = 102;
long l = i; //Implicit type casting
double d = l; //Implicit type casting
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Double value "+d);
}
}
● Save the file as CastExample.java.
Output:
>java CastExampleInt value 102
Long value 102
Double value 102.0
2.Explicit casting(narrowing conversion)
Example:
/*explicit type casting program in java.*/
//programming789.blogspot.com/
public class CastExample
{
public static void main(String[] args)
{
double d = 102.04;
long l = (long)d; //explicit type casting
int i = (int)l; //explicit type casting
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
● Save the file as CastExample.java.
Output:
>java CastExample
Double value 102.04Long value 102
Int value 102