Java

Type Casting

Java / Type Casting

Type Casting

Type Casting

Type casting in Java is the process of converting one data type into another data type.

It is used when we want to assign a value of one data type to a variable of another data type.

Types of Type Casting in Java:

In Java, there are two main types of type casting

1. Widening Type Casting (Automatic) converting a smaller type to a larger type size

byte -> short -> char -> int -> long -> float -> double

  • Converts a smaller data type into a larger data type
  • Done automatically by Java
  • No data loss

2. Narrowing Type Casting (Manual) converting a larger type to a smaller type size

double -> float -> long -> int -> char -> short -> byte

  • Converts a larger data type into a smaller data type
  • Done manually by the programmer
  • May cause data loss

Example

public class Main {
Β public static void main(String[] args) {

Β  Β  Β  // Β WIDENING CASTING (Automatic)

Β  Β int myInt = 9; Β  Β  Β  Β  Β  Β  Β  Β  // int type (smaller size)
Β  Β double myDouble = myInt; Β  Β  Β  // int β†’ double (automatic conversion)

Β  Β  System.out.println("int value: " + myInt);
Β  Β System.out.println("double value: " + myDouble);

Β  Β  Β  // Β NARROWING CASTING (Manual)

Β  Β double myDouble2 = 9.78; Β  Β  Β  // double type (larger size)
Β  Β int myInt2 = (int) myDouble2; Β // double β†’ int (manual casting)

Β  Β  System.out.println("double value: " + myDouble2);
Β  Β System.out.println("int value: " + myInt2);
Β }
}

Technology
Java
want to connect with us ?
Contact Us