print
Advertisment
Advertisment

type cast operators in java

The process of converting the value of one data type to the value of another data type is called type casting. In this we cast the value of one type to another type.When we assign the value of one data type to another data type, it may happen that both those types are not compatible with each other. And if both types are compatible. Then Java does the conversion automatically. Which is called automatic type conversion. If they are not compatible then they need to do type cast (conversion data type).

We have two types of this operators

  1. implicit type casting in java
  2. Explicit type casting in java

Implicit type casting

Implicit type casting then occurs. When both data types are converted automatically. This happens when:-

  • When both the data types are compatible with each other.
  • When we assign the value of small data type to any one big data type.
  • The compiler is responsible to perform this type casting.
  • It is also known as Widening or Upcasting
  • There is no lose of information in this type casting.

Example

		
	class Automatic_casting {
		public static void main (String args []) {
			int i = 130;
			long l = i;
			float f= l;
			System.out.println("int value = " + i);
			System.out.println("long value = " + l);
			System.out.println("float value = " + f);
		}
	}
		
	

Output :

	
	
		int value = 130
		long value = 130
		float value = 130.0
	

Advertisment

Explicit type casting in java

Narrowing Casting:This type of type casting is done when:-

  • When both the data types are not compatible with each other.
  • When we assign the value of a large data type to a smaller data type.
  • Also known as Narrowing or down casting.
  • There may be a chance of lose of information in this type casting.

Example

		
	class Narrowing_casting {
		public static void main (String args []) {
			double d = 3456.45;
			float  f =457.4f;
			long l = (long)d;
			int i = (int)f;
			System.out.println(l);
			System.out.println(i);
		}
	}
		
	

Output :

	
	
		3456
		457
	
Advertisment
Advertisment
arrow_upward