Type Casting in Java

Java type casting is used to assign a value of one type to a different type of variable, i.e. converting data from one data type to another data type. In Java, there are two types of casting.

  1. Implicit Casting
  2. Explicit Casting

Representation of Java Type Casting

java type casting

Syntax for Type Casting

The syntax for type casting is:

newDatatype variableName= (newDatatype) variableToConvert;

Did you know?

While doing implicit type casting, type casting is done automatically. What does that mean? It means while doing implicit typecasting we can neglect the (newDatatype) and the compiler would understand what we are doing. Hence our syntax would become:

newDatatype variableName= variableToConvert;

Java Type Casting Example

So, reiterating what we discussed above, an Implicit type casting occurs when the value of a variable having a certain data type is stored in another variable whose datatype has more memory space than the former one. And, an Explicit type casting occurs when the value of a variable having a certain data type is stored in another variable whose datatype has lesser memory space than the former one. With that in mind let us look at an example.



public class Test {
public static void main(String[] args) {
byte a=10;
short b=a;  //Implicit type cast
System.out.println(b); //10

short c=300;
byte d=(byte)c;  //Explicit type cast
System.out.println(d); //44

int e=100;
float f=(float)e; //Implicit type cast, note the default syntax
System.out.println(f); //100.0 

long g=(long)f;  //Explicit type cast
System.out.println(g); //100,
}	
}