cast Operator is used to convert one data type into anotherdatatype.
primitive type casting:There are two types of primitive type castin

  1. implicit typecasting
  2. explicit type casting

implicit type casting:

  • compile is responsible for this type casting
  • This type of typecasting is required when ever we are assigning smaller data type value to the bigger data type variable
  • It is also known as “Widening” on”upcasting”.
  • No loss of information in implicit type castings

The following are all possible implicit type casting
byte—>short—–>int—->long—->float—–>double
Example:


public class Test {
 public static void main(String[] args) {
  double d=10;
  System.out.println(d);
 }
}
/*
Output:
10.0
*/

Compiler automatically converts int value to the double type by implicit type casting.
Example:


public class Test {
 public static void main(String[] args) {
  int i='a';
  System.out.println(i);
 }
}
/*
Output:
97
*/

Explicit type casting:

  • It is the responsibility of programmer.
  • It requires,when ever we are assigning bigger data type value to the smaller datatype variable
  • There may be a chance of loss of information
  • The following are all possible conversions which requires explicit type casting
    Example:

    
    public class Test {
     public static void main(String[] args) {
      byte b=(byte)130;
      System.out.println(b);
     }
    }
    Output:
    -126
    
  • It also known as “narrowing” (or)”downcasting”
    Example:

    
    public class Test {
     public static void main(String[] args) {
      int i=150;
      byte b=(byte)i;
      short s=(short)i;
      System.out.println(b);
      System.out.println(s);
     }
    }
    /*
    Output:
    -106
    150
    */
    

    Example:

    
    public class Test {
     public static void main(String[] args) {
      double d=130.4567;
      byte b=(byte)i;
      int s=(int)i;
      byte b=(byte)i;
      System.out.println(b);
      System.out.println(s);
     }
    }
    /*
    Output:
    130
    -126
    */
    
  • When ever we are assigning floating point values to the integral types by explicit type casting the digits after decimal point will be lost.