Java Type Casting - IndianTechnoEra
Latest update Android YouTube

Java Type Casting

 

Java Type Casting

Assign a value of one primitive data type to another type. 

In Java, there are two types of casting:

i. Widening Casting (automatically)

ii. Narrowing Casting (manually)



Widening Casting

Widening Casting perform automatically

Converting a smaller type to a larger type size.

Widening casting is done automatically when passing a smaller size type to a larger size type:


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


Example:

public class Main {

  public static void main(String[] args) {

    int myInt = 9;

    double myDouble = myInt; // Automatic casting: int to double

    System.out.println(myInt);      // Outputs 9

    System.out.println(myDouble);   // Outputs 9.0

  }

}



Narrowing Casting 

Narrowing Casting needs to perform manually

Converting a larger type to a smaller size type. 

They must be done manually by placing the type in parentheses in front of the value.


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


Example:

public class Main {

  public static void main(String[] args) {

    double myDouble = 9.78d;

    int myInt = (int) myDouble; // Manual casting: double to int

    System.out.println(myDouble);   // Outputs 9.78

    System.out.println(myInt);      // Outputs 9

  }

}

Post a Comment

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.