Java Type Casting

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 size

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

Let's saw some program of automatic type casting:

package com.ritesh;
public class TypeCaster {
public static void main(String[] args) {
int x=10; //giving the value 10 in integer x;
double y=x; //value y in x;
System.out.println("The value of x is "+x );
System.out.println("The value of y is "+ y);
}
}

It is easy to convert the integer datatype into double datatype.

Let's saw some program of manually type casting..


package com.ritesh;
public class TypeCaster {
public static void main(String[] args) {
double d1=4.55;
int d2=(int)d1;
System.out.println("the value of d1 is "+d1);
System.out.println("The value of d2 is "+ d2);
}
}


Comments