Translate

Monday 11 August 2014

Datatype Conversion in java

Let's take an example
int a = 25;
double b = 3.14;
a = b;      //compile time error
In c language this is not an error and a would become 3. But in java narrowing of datatype is not allowed.
As discussed in http://javaproglearner.blogspot.in/2014/08/data-types-in-java.html size of datatype varies from 1 byte(8 bit) to 8 bytes(64 bits). So if you want to assign a double value to integer basically you are trying to store data of 8 bytes into 4 bytes. Java does not support this. It is a compile time error.

But,
a = (int) b;
This statement is valid. This is known as explicit typecast. In simple language here we are asking a double type variable b to behave like an integer and then assigning it to integer variable a.

Similarly,
int a = 25;
float b = 6.2f;
double d = 9.14;
a = (int) b;
b = (float) d;

These are all valid statements.

No comments:

Post a Comment

Total Pageviews