Type Casting in Java.

Implicit type casting in java

Implicit Casting: A lower size data type can be assigned to a higher size data type automatically. It is also called Widening.

byte -> short -> char -> int -> long -> float -> double

Example: char c = 'A';

                int i = c;

Explicit Casting: A higher size data type can be assigned to a lower size data type manually. It is also called Narrowing. 

double -> float -> long -> int -> char -> short -> byte

Example: long val = 10;

                 int x = (int)val;

Example of Implicit Casting.

public class Main
{
	public static void main(String[] args) {
		int x = 8;
		double y = x; //Implicit casting
		System.out.println(x);
		System.out.println(y);
		
	}
}
Output
8
8.0

Example of Explicit Casting.

public class Main
{
	public static void main(String[] args) {
		double x = 8.23;
		int y = (int)x; //Implicit casting
		System.out.println(x);
		System.out.println(y);
	}
}
Output:
8.23
8

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS