Dan
Dan

Reputation: 45

how to do type conversion for pointer type in java like in c/c

In c/c++, one can do things like

float b = 3.;
int a = *(int*)&b;

I want to do the same thing in java, is it possible and if so, how?

Thank you.

Upvotes: 1

Views: 1261

Answers (4)

lightbringer
lightbringer

Reputation: 835

Java implements everything based on pointers. So any object variable in Java will be passed as pointer reference. They made it invisible to Java developer. To convert from float or double to int, you can simply try

double b = 3.0;
int a = (int)b;

Be aware that if b = 1.x then a = 1

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Pointers are not available in java. You have to work with Object.

Float f = new Float(3.0);
Integer i = Math.round(f);

Upvotes: 2

Vimal Bera
Vimal Bera

Reputation: 10497

There is no POINTER kind of thing in JAVA. JAVA has a feature called Memory Management or say GC(Garbage collector) to handle all the memory related operations for you. You are not allowed to access any memory block by using memory address.

Upvotes: 3

zneak
zneak

Reputation: 138051

Java doesn't have pointers. For this specific case, you can use Float.intBitsToFloat (and Float.floatToIntBits for the other way; Double also has similar methods). There is, however, no way to do funkier "conversions".

Upvotes: 4

Related Questions