vanshitatiwari
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: "Type Casting in Java - Scaler Topics" description: "Learn about Type Casting in Java by Scaler Topics. Typecasting is mainly of two types in JAVA. 1. Widening or automatic Casting 2.Narrow or explicit Casting." author: "Aayush Kumar" category: "Java" --- :::section{.abstract} ## Overview The process of converting one data-type to another data-type is termed `type casting`. Sometimes, while we are writing a program, we need to convert one data-type to another data-type. A `String` containing digits can be converted to an integer, an integer can be converted to a string, an integer can be converted to double, etc. `Type casting` can be done both manually and automatically. Type Casting happens automatically when a value of one primitive data type is assigned to another data type. There are two types of casting: **Widening Type Casting** and **Narrowing Type Casting**. ::: :::section{.scope} ## Scope This article aims to: - Explain what is type casting Java with examples and it's types - Illustrate Widening and Narrowing Type Castings - Explain Explicit Downcasting and Explicit Upcasting through examples - Is type casting important in Java? we provide examples where type casting is useful ::: :::section{.main} ## Introduction First of all, let’s understand the literal meaning of **Type Casting** with context to programming. **Type** means the data type of a variable or entity and **Casting** means converting the data type of an entity to another data type. The compiler performs the automated conversion, and the programmer handles the manual conversion. ::: :::section{.main} ## What is Type Casting/Conversion in Java? The act of allocating a value from one primitive data type to another is known as **Type Casting**. You should consider the compatibility of the data type before assigning a value from one data type to another. If they are compatible, Java will automatically execute the conversion known as Automatic Type Conversion; if not, they must be cast or manually converted. ### Example Let us see a quick example where we will convert a string to an integer using `Integer.parseInt()` method in Java. **Code:** ```java public class StringtoInt { public static void main(String args[]) { // Declaring String variable String s = "1000"; // Convert to int using Integer.parseInt() int i = Integer.parseInt(s); // Printing value of i System.out.println(i); } } ``` **Output:** ```java 1000 ``` **Explanation:** * We have created a String variable `s` in the code above. * Next, we have converted the string variable to an integer using `Integer.parseInt()` method. ::: :::section{.main} ## Types of Casting in Java Typecasting is mainly of two types in JAVA. 1. Widening Type Casting 1. Narrow Type Casting ### Widening Type Casting `Widening type casting` refers to the conversion of a lower data type into a higher one. It is also known as implicit type casting or casting down. It happens on its own. It is secure since there is no possibility of data loss. Widening Type Casting happens on the following scenarios or conditions: * **Both the data types must be compatible with each other.** For example, converting a string to an integer is not possible as the string may contain alphabets that cannot be converted to digits. * The target variable holding the type casted value must be larger than the value being type casted. ![Widening Type Casting](https://www.scaler.com/topics/media/Widening-Type-Casting.webp) In the above image, `double` is larger data type than `float`, `long`, `int`, etc. Similarly, `int` is larger data type than `short` and `byte`. When converting from a lower data type to a larger data type, no loss of data occurs as the range of supported values is wider in the larger data type. Let’s understand the concept of Widening Type Casting with the below examples. In the first example, the `long` datatype value is automatically cast to the `double` datatype and the `int` data type value is automatically cast to the `long` datatype by the java compiler. ### Example ```java public class WideningTypeCastingExample { public static void main(String[] args) { int i = 10; // Automatic Casting from int to long long l = i; // Automatic Casting from int to double double d = i; System.out.println("int i = " + i); System.out.println("long l = " + l); System.out.println("double d = " + d); } } ``` ### Output: ```java int i = 10 long l = 10 double d = 10.0 ``` ::: :::section{.main} ## Narrow Type Casting (on default data types) Narrowing type casting refers to the conversion of a larger data type into a lower one. It is also known as explicit type casting or casting up. It does not happen on its own. *We must do it explicitly otherwise compile-time error is thrown.* **Narrowing type casting is not secure** as loss of data can occur due to shorter range of supported values in lower data type. Explicit Casting is done with the help of `cast` operator. ### Syntax ```java // var is of lowerDataType var = (lowerDataType) expr; ``` ![Explicit Type Casting Order](https://www.scaler.com/topics/media/Explicit-Type-Casting-Order.webp) In the above image, `int` is a lower data type as compared to `double`, `float`, `long`, etc. When we convert a `long` to an `int`, it is possible that the value of the `long` variable is out of range of `int` variable. Let’s understand the explicit casting with the help of the examples. In the first example, we explicitly convert the double data type into two small priority data types. Double data type values lose precision and the range is updated according to the short and int data types range. ### Example 1: ```java public class NarrowingTypeCastingExample { public static void main(String[] args) { double a = 100.245; // Narrowing Type Casting short b = (short) a; int c = (int) a; System.out.println("Before Casting Original Value " + a); System.out.println("After Casting to short " + b); System.out.println("After casting to int " + c); } } ``` ### Output: ```java Before Casting Original Value 100.245 After Casting to short 100 After casting to int 100 ``` **Explanation:** * As it is visible in the code, there is loss of decimal digits after conversion from `double` to either `short` or `int`. * We perform explicit type casting using the cast `()` operator and mentioning the name of target data type inside the brackets. ### Lossy Narrowing Type Casting **Example of data loss:** ```java long l = 2147483648L; // // T // And we are trying to store a value in i // greater than its upper limit int i = (int) l; ``` ```java public class LossyConversion { public static void main(String[] args) { long l = 2147483648L; int i = (int) l; System.out.println(i); } } ``` **Output:** ```java -2147483648 ``` **Explanation:** * As you can see the output, `i` contains **-2147483648**. This is because the range of `int` is `-2147483648` to `2147483647`. * And we are trying to store a value in `i` greater than its upper limit resulting in overflow situation. ### Explicit Type casting on user-defined datatypes Explicit type casting can also be used on the user-defined datatypes i.e on objects. Let’s understand with the help of the below example why we need type casting on user-defined data types. ```java class Parent { String name = "Parent class"; void call() { System.out.println("This is Parent class method"); } } class Child extends Parent { int number = 1; String name = "Child class"; public static void main(String[] args) { Parent ob = new Child(); System.out.println(ob.number); } } ``` **Output:** ```java Main.java:18: error: cannot find symbol System.out.println(ob.number); ^ symbol: variable number location: variable ob of type Parent 1 error ``` **Explanation:** * In the above example, we have created a reference variable `ob` of type `Parent` which is pointing to an object of `Child` class. * Now, using ob, we cannot access the members of Child class such as number. It is because the type of reference variable is still Parent. * Here, we have to use type casting to access the attributes of Child class. Let's use type casting above to achieve desired results: **Code:** ```java class Parent { String name = "Parent class"; void call() { System.out.println("This is Parent class method"); } } class Child extends Parent { int number = 1; String name = "Child class"; public static void main(String[] args) { Parent ob = new Main(); Child ch = (Child) ob; System.out.println(ch.number); } } ``` **Output:** ```java 1 ``` ## There are two types of Explicit Casting 1. Explicit Downcasting 1. Explicit Upcasting ![two types of casting possible in java](https://www.scaler.com/topics/media/two-types-of-casting-possible-in-java.webp) Let’s understand the working of both types of casting. ### Explicit Upcasting In explicit upcasting, an object of `Child` class is explicitly typecast to the `Parent` class object. With the help of explicit upcasting, we can access the methods and variables of the `Parent` class to the `Child` class. Please note we cannot access all methods and variables of the `Parent` class. This is because due to the inheritance, overriding methods still have access to the `Child` class, not the `Parent` class. Let’s understand this concept using an example. ### Example: ```java class Parent { String name = "Parent class"; void call() { System.out.println("This is Parent class method"); } } class Child extends Parent { int number = 1; String name = "Child class"; void call() { System.out.println("This is Child class method"); } public static void main(String[] args) { Child ob = new Child(); // Upcasting Parent pr = (Parent) ob; // Calling name of Parent class System.out.println(pr.name); //call() method is called of Child class not Parent class ob.call(); } } ``` ### Output: ```java Parent class This is Child class method ``` ### Explicit Downcasting `Explicit Downcasting` occurs when we assign a parent class reference to a child class reference. In Java, in some cases, **we can perform downcasting when a subclass object is referred through a parent class reference.** We have to explicitly assign a child class reference because if we implicitly assign the child class reference to the parent class it will be a violation of the inheritance rule and give a compilation error. However, we can use explicit downcasting to solve this issue. Let us see an example: ### Example: ```java class Parent { String name = "Parent class"; void call() { System.out.println("This is Parent class method"); } } class Child extends Parent { int number = 1; String name = "Child class"; void call() { System.out.println("This is Child class method"); } public static void main(String[] args) { // Create an object of Child class and point to it // Using reference variable of type Parent Parent ob1 = new Child(); // Explicit downcasting Child ob = (Child) ob1; ob.call(); System.out.print(ob.name); } } ``` ### Output: ```java This is Child class method Child class ``` ### Quick understanding of upcasting and downcasting ![upcasting and downcasting in type casting in Java](https://www.scaler.com/topics/media/upcasting-and-downcasting.webp) ::: :::section{.main} ### When does Automatic type conversion occur in Java? The two types of data may not be compatible when you assign a value of one to the other. If the data types are compatible, Java will convert them automatically. This is known as **Automatic Type Conversion**. Otherwise, they must be cast or explicitly converted. ::: :::section{.main} ## Difference between Type Casting and Type Conversion |Type Casting |Type Conversion | |-----|--------| |In type casting, a programmer uses the casting operator to change one data type into another.| While a compiler transforms a data type into another data type via type conversion. | |Both incompatible and compatible data types are subject to type casting. |Type conversion, however, can only be used with suitable datatypes. | |A casting operator is required in type casting in order to convert one data type to another data type. |In contrast, a casting operator is not required for type conversion. | |When typing casts a data type into another data type, the destination data type could be smaller than the source data type. |The destination data type cannot be smaller than the source data type in type conversion, though. | |When a programmer designs a programme, type casting occurs. |Type conversion, however, happens during compilation. | |Due to the possibility that the destination data type may be smaller than the source data type, type casting is also known as narrowing conversion. |Alternatively known as widening conversion, type conversion prevents the destination data type from being smaller than the source data type. | |In coding and competitive programming tasks, type casting is frequently utilised. |While type conversion is less common in programming competitions since it could result in wrong answers. | |Type casting is more dependable and efficient. |Type conversion, however, is less dependable and efficient. | ::: :::section{.main} ## Application of Typecasting ### 1. Explicit type casting The most common example of Explicit type casting is finding an accurate average of the given numbers. If we use widening casting the precision of the average will not be included in the average but if explicitly typecast the expression using the typecast operator, we will get an accurate average of the given numbers. ### 2. Automatic type casting The most common example of `automatic type casting` is when we have multiple arithmetic expressions of mixed data types and we have to perform operations on them. In this case, automatic or widening type casting is used to get the accurate answer to the given expression. ::: :::section{.summary} ## Conclusion - Type casting refers to the process of converting one data type to another data type. - There are mainly two types of Type Casting: Widening Type Casting and Narrow Type Casting. - The process of conversion of higher data type to lower data type is known as narrowing typecasting. It is also known as Explicit TypeCasting as it must be done explicitly. - The process of conversion of lower data type to higher data type is known as widening typecasting. It is also called Implicit TypeCasting as it can be done implicitly by the compiler. - There are two types of Explicit TypeCasting: Explicit Downcasting and Explicit Upcasting that can be used on user-defined objects and classes. - When a parent class reference is assigned to a Child class object, it is called Explicit Upcasting. - When a parent class reference variable pointing to a Child class object is assigned to a Child class reference variable, it is called Explicit Downcasting. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully