Type Casting and Conversion

Type Casting and Conversion – Implicit and Explicit Conversion

We all know about basic data types like int, short, long, float and double etc with their size and limit. In this blog we will discuss of type casting and conversion on this primitives data types. In Java program two types of casting available. One is automatically (implicit) and second is manually (explicit). Both are very different from each other. Let’s see both type one by one.

  1. Implicit Conversion [Automatically]

In all data type double has maximum rang, so we can easily assign int,short types value to double automatically so this type of conversion or casting called implicit conversion. Let’s take one simple example and understand the topic. In this first example, int r automatically converts into double area.

Program in Implicit Conversion:

Title: Implicit Conversion

class type1

{

public static void main(String args[])

{

int r = 100;

double pi = 3.14;

double area = pi*r*r; // implicit type casting

System.out.println(“Area = ” + area);

}

}

Output:

Area = 314.00

 

Video available on  YouTube.

 

  1. Explicit Conversion [Manually]

In all data type double has maximum rang, so we cannot easily assign into int, short types value so this type of conversion or casting called explicit conversion. Let’s take one simple example and understand the topic. In this second example, double pi manually converts into int area.

Program in Explicit Conversion:

Title: Explicit Conversion

class type2

{

public static void main(String args[])

{

int r = 100;

double pi = 3.14;

//int area = (int)(pi*r*r); // explicit type casting  OP1

int area = (int)(pi)*r*r; // explicit type casting    OP2

System.out.println(“Area = ” + area);

}

}

Output:

Op1 :->  Area = 314

Op2 :-> Area = 300

 

Video available on YouTube.

 

[sbscrbr_form]

If you have problem on this blog, you can directly comment or subscribe on website.

517total visits,6visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image