You can use class sun.misc.Unsafe, that lets you work with the JVM memory directly.
Its constructor is private, So you can get an Unsafe instance like this:
public static Unsafe getUnsafe() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe)f.get(null);
} catch (Exception e) { /* ... */ }
}
You can then get your string bytes with:
byte[] value = []<your_string>.getBytes()
long size = value.length
You can now allocate the memory size and write the string in RAM:
long address = getUnsafe().allocateMemory(size);
getUnsafe().copyMemory(
<your_string>, // source object
0, // source offset is zero - copy an entire object
null, // destination is specified by absolute address, so destination object is null
address, // destination address
size
);
// the string was copied to off-heap
Source: https://highlyscalable.wordpress.com/2012/02/02/direct-memory-access-in-java/