Type Casting in Java

Type Casting in Java

Type Casting in Java

In this Blog Post, we can study about “Type Casting in Java”.

The casting is a process of changing a value of one type into another type.

When you can assign a value of one data type to the value of other datatypes then you need to must aware of the compatibility of the datatype.

There are two type casting in java such as:

  • Widening casting in java (automatically) = This will convert a small datatype value into large datatype.
  • Narrowing casting in java(manually) = This will convert a larger datatype value into a smaller datatype.

Widening casting in java

Type Casting in Java

This type of casting will take place when both data types are automatically converted.

This casting is also known as implicit casting.

Widening casting will happen only when the two data types are compatible with each other and also assign smaller datatype to larger datatype.

In this casting, the target type is always larger than the source type.


public class sample{

public static void main(String[] args) {

int myInteger = 9;

double myDoubletype = myInteger; // This line will Automatic casting: int to double


System.out.println(myInteger);      // Outputs will be 9

System.out.println(myDoubletype);   // Outputs will be 9.0





Narrowing casting in java

When you want to assign a larger datatype value to smaller datatype value then this typecasting called Narrowing typecasting.

This typecasting is also called Explicit typecasting.

The Narrowing casting useful for incompatible datatype and useful when the automatic conversion cannot be done.

If you don’t perform casting then the compiler will produce the compile-time error.

This casting is done manually.


public class Sample


public static void main(String[] args)


double doubletype = 100.04;

long longtype = (long)doubletype;  // it requires explicit type casting required

int integertype = (int)longtype; //explicit type casting required

System.out.println(“Double value “+doubletype);

System.out.println(“Long value “+longtype);

System.out.println(“Int value “+integertype);




Double value 100.04

Long value 100

Int value 100


Also Read This:

What is this keyword in java?

What is Java Programming Language?


Hey Friends, Welcome to thetechbuddy. This blog is about technical or programming knowledge.

Leave a Reply