Logan Hartman
Logan Hartman

Reputation: 51

Using ".printf(...)" in Java to print the value in memory

To begin: Yes, I know there exist similar questions regarding this, but primarily in other languages or doing other operations

I would like to print out the values, located in memory, of a variable. As in, the exact value, not the variable name.

For an integer value, I would like to print out the binary representation of whatever is located in binary. This can easily be done with conversions, but I'd like to use the value in memory for an example.

For a floating-point value, I again would like to print out exactly what is stored in memory, again as an example (for a research paper presentation).

For a non-primitive value, I would like to print out the address located in the variable's allocated space.

How would I do this? It doesn't necessarily have to use the "printf" method; I remember someone mentioning to me that it was possible to do it using "printf".

It was brought up that in Java you are unable to access the addresses in memory. Is it possible to access the values in memory themselves for primitive values? Or, would I be better off attempting to switch to another language?

Upvotes: 0

Views: 409

Answers (1)

Andreas
Andreas

Reputation: 159086

Java does not give you direct access to anything stored in memory. The JVM is free to store any value in whatever form it wants, as long as it behaves as described in the Java Language Specification. So your request is impossible.

You can get some "internal" values, but it may not be what's in memory.

For an integer value, I would like to print out the binary representation of whatever is located in binary.

Use Long.toBinaryString(long) or Integer.toBinaryString(int).

For a floating-point value, I again would like to print out exactly what is stored in memory.

Use Double.doubleToRawLongBits(double) or Float.floatToRawIntBits(float), then convert to binary as above.

For boolean, the value is either true or false. No internal representation is defined, e.g. a boolean[10] may be stored as 10 64-bit values of 0 or 1 (unlikely), as 10 bytes (likely), or as 2 bytes using the lower 10 bits. JVM's choice.

For a non-primitive value, I would like to print out the address located in the variable's allocated space.

Not possible. These days, Java references are usually stored internally as a 32-bit Compressed OOP, but you can't get it.

Upvotes: 3

Related Questions