24 May 2010

Casting in C vs Java

Al salamo Alykom,

I will talk about casting for primitive types in Java vs in c.

suppose we have two numbers: float f and int i:

1- the following in valid in both languages:
f = i;
2- the following is valid only in c, and will cause compilation error in java:
i = f; // in java, it should be i = (int) f;
3- promotion rules (applies in both):
int x = 10;
float d = x / 3.0f; // result is 3.333333, NOTE, the f of 3.0f only required in Java

int x = 10;
float d = x / 3; // result is 3

int x = 10;
float d = (float)x / 3; // result is 3.333333

No comments: