Type Casting In Java

In a simple word if you try to assign one data type to another type then needed type casting. That means it is used to convert an object or variable of one type into another.


dataType variableName = (dataType) anotherVariableToConvert;

Type Of Type casting

There are two types of casting.

  1. Automatic or Widening Casting
  2. Narrowing or Explicit Casting

Automatic or Widening Casting

Word automatic means “itself”. It is simple in java, It automatically converts one data type to another data type when passing a smaller size type to a larger size type. It is also known as Implicit type casting.

Example: Converting int to double

public class IntToDouble {  
    public static void main(String args[]){  
    	int num = 909;
        // convert into double type
        double cvalue = num;
        System.out.println("int value: " + num);
        System.out.println("double value: " + cvalue); 


int value: 909
double value: 909.0

Narrowing or Explicit Casting

By using parenthesis in front of the value we manually convert one data types into another types that is known as Narrowing or Explicit Casting. It converting a larger size type to a smaller size type

Example: Converting double into an int

public class DoubleToInt {  
    public static void main(String args[]){  
    	double num = 909;
        // convert into int type
        int cvalue = (int)num;
        System.out.println("double value: " + num);
        System.out.println("int value: " + cvalue); 


double value: 909.0
int value: 909
Do you know?
Type Casting In Java This article is contribute by Study4Geeks If you want share your knowledge on Study4Geeks then go to login section.