Java Variable Type Conversion & Type Casting - CodingAliens

Java Variable Type Conversion & Type Casting

The value of one primitive data type assigns to the another data type is known as type casting or java variable type conversion. 
Here there are 2 types -

1) Automatic type casting(widening casting)  = small - 2 - large

Variable of smaller capacity is be assigned to another variable of bigger capacity.

  • byte -> short -> char -> int -> long -> float -> double
int myInt = ;
double myDouble = myInt ;
This process is Automatic, and non-explicit is known as Conversion


public class MyClass {
  public static void main(String[] args) {
    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double

    System.out.println(myInt);      // Outputs 11
    System.out.println(myDouble);   // Outputs 11.0
  }
}

 2) Manual type casting (narrowing casting) = large - 2 - small

Variable of larger capacity is be assigned to another variable of smaller capacity
  • double -> float -> long -> int -> char -> short -> byte

  int a;
  double d = 128.128;
  a = (int) d;


In such cases, you have to explicitly specify the type cast operator. This process is known as Type Casting.


In case, you do not specify a type cast operator; the compiler gives an error. Since this rule is enforced by the compiler, it makes the programmer aware that the conversion he is about to do may cause some loss in data and prevents accidental losses.

Example: How Manual Type Casting works

class CodingAliens {
public static void main(String args[]) {
  byte x;
  int a = 271;
  double b = 128.128;
  System.out.println("int converted to byte");
  x = (byte) a;
System.out.println("a and x " + a + " " + x);

  System.out.println("double converted to int");
  a = (int) b;
  System.out.println("b and a " + b + " " + a);

  System.out.println("\ndouble converted to byte");
  x = (byte) b;
  System.out.println("b and x " + b + " " + x);
}
}
Output:


int converted to byte
a and x 271 14
double converted to int
b and a 128.128 128

double converted to byte
b and x 128.128 -128

Post a Comment

0 Comments