Typecasting in Java

Typecasting is used to temporarily change the data type of a value. There are two types of data in Java:

  1. Primitive data types
  2. Non-primitive data types

Java supports widening casting and narrowing casting.

svg viewer

Widening casting

Widening casting changes a smaller data type to a larger data type. For example, byteshortcharintlongfloatdouble.

This type of casting is usually automatic; you do not need to use().

Narrowing casting

Narrowing casting changes the data type from a larger data type to a smaller data type. For example, doublefloatlongintcharshortbyte.

Code

Widening casting

class myClass {
public static void main( String args[] ) {
int number = 7;
double doubleNumber = number; // Widening casting: int to double
System.out.println(number); // 7
System.out.println(doubleNumber); // 7.0
}
}

Narrowing casting code

class myClass {
public static void main( String args[] ) {
double number = 7.3;
int intNumber = (int) number; // Narrowing casting: int to double
System.out.println(number); // 7.3
System.out.println(intNumber); // 7
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved