Table of Contents

Java Type Casting

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

  • Widening Casting (automatically) - converting a smaller type to a larger type sizebyte -> short -> char -> int -> long -> float -> double
  • Narrowing Casting (manually) - converting a larger type to a smaller size typedouble -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type:

public class Main { public static void main(String[] args) { int valueInt = 8; double valueDouble = valueInt; // Automatic casting: int to double System.out.println(valueInt); // Outputs 8 ( displays the valueInt value ) System.out.println(valueDouble); // Outputs 8.0 (the integer 8 is automatically converted into double data type . so it results 8.0 . } }

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of the value.

syntax:

type variable1 = (type) variable2;

Example:

public class Main { public static void main(String[] args) { double valueDouble = 8.79; int valueInt = (int) valueDouble; // Manual casting: double to int System.out.println(valueDouble); // Outputs 8.79 ( results the myDouble value 8.79) System.out.println(valueInt); // Outputs 8 ( myDouble value 8.79 is manually converted into integer type by using the int data type name in parentheses. } }

here (int) is the used in parentheses in front of the value to convert double data type to int data type.

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?