Develop a program for implementation of implicit type casting in Java. Part-II

 Welcome to Part II of our series on implicit type casting in Java. In this article, we'll continue exploring the concept of implicit type casting and develop a more advanced program to demonstrate its implementation in various scenarios.

Recap of Implicit Type Casting:

Before we delve into our program, let's briefly recap implicit type casting in Java. Implicit type casting, also known as type coercion, refers to the automatic conversion of one data type to another by the Java compiler. This conversion occurs to ensure data compatibility and prevent data loss when performing operations or assignments involving different data types.

Developing an Advanced Program:

In this program, we'll explore several scenarios where implicit type casting comes into play. We will calculate the area of a rectangle using user input for length and width, and then display the result as a double.

Code:

import java.util.Scanner;

public class ImplicitTypeCastingDemoPart2 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the length of the rectangle: ");

        int length = scanner.nextInt();

        System.out.print("Enter the width of the rectangle: ");

        double width = scanner.nextDouble();

        double area = length * width; // Implicit type casting from int to double

        System.out.println("Area of the rectangle: " + area);

        scanner.close();

    }

}


Output:
Enter the length of the rectangle: 10
Enter the width of the rectangle: 4.5
Area of the rectangle: 45.0

In this program, we calculate the area of a rectangle based on user input. The length is read as an int, and the width is read as a double. During the multiplication operation, implicit type casting occurs as the int value (length) is automatically converted to a double to perform the multiplication without data loss.

Additional Scenarios for Implicit Type Casting:

Implicit type casting can also occur in other scenarios, such as:
  • Combining different numeric types in arithmetic operations.
  • Assigning a smaller numeric type to a larger one without explicit casting.
  • Using characters in arithmetic operations (converted to their Unicode values).

Comments