Pages

Tuesday, 17 May 2022

Type casting

Type casting is nothing but assigning a value of one primitive data type to another. When you assign the value of one data type to another, you should be aware of the compatibility of the data type. If they are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not, then they need to be casted or converted explicitly.
There are two types of casting in Java as follows:
Widening Casting(Implicit or automatically)
This type of casting takes place when two data types are automatically converted. It is also known as Implicit Conversion. This happens when the two data types are compatible and also when we assign the value of a smaller data type to a larger data type.This involves the conversion of a smaller data type to the larger type size.
byte -> short -> char -> int -> long -> float -> double
  1            2          2          4         8           4               8   

Example on Implicit:
public class Widening
{
public static void main(String[] args)
{
int x=20;
float b=x;//up casting
System.out.println("Implicit Data type value "+b);
char ch='a';// asci value of a=97
int z,y=10;
z=y+ch;  // 107=10+97 //up casting
System.out.println("Implicit Data type value "+z);
}
}
Output:
C:\Users\student\Desktop>javac Widening.java
C:\Users\student\Desktop>java Widening
Implicit Data type value 20.0
Implicit Data type value 107

Narrowing Casting(Explicit or manually)
In this case, if you want to assign a value of larger data type to a smaller data type, you can perform Explicit type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be done.This involves converting a larger data type to a smaller size type. 
double -> float -> long -> int -> char -> short -> byte
   8              4          8            4         2          2           1

Syntax:
(datatype) variable

Example  on Narrowing:
public class Narrowing
{
    public static void main(String[] args)
    {
    int x=10;
    int y=3;
    float z =(float)x/y;  //down casting
    System.out.println("Explicit Data type value "+z);
    
    int q=233;// 11101001  2's complement = 00010111 = -23
    byte p =(byte)q;  //down casting
    System.out.println("Explicit Data type value "+p);
    }
}
Output:
C:\Users\student\Desktop>javac Narrowing.java
C:\Users\student\Desktop>java Narrowing
Explicit Data type value 3.3333333
Explicit Data type value -23
 

No comments:

Post a Comment

Servlet - JSP Programs

JSP(Java Server Pages) Programs : JavaServer Pages (JSP) is a Java standard technology that enables you to write dynamic data-driven pages f...