0

Where is the intern() method - which is used to place string literals from heap - defined? I see only the declaration in the String class; not the definition.

SusanW
  • 1,550
  • 1
  • 12
  • 22
user3103957
  • 636
  • 4
  • 16

1 Answers1

2

The definition of the intern method says this:

public native String intern();

and the native bit means it's a native method, hooked into the JVM at runtime. The original code is written is C++, and you can find the source here around line 3866:

http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/tip/src/share/vm/prims/jvm.cpp

It says:

JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
  JVMWrapper("JVM_InternString");
  JvmtiVMObjectAllocEventCollector oam;
  if (str == NULL) return NULL;
  oop string = JNIHandles::resolve_non_null(str);
  oop result = StringTable::intern(string, CHECK_NULL);
  return (jstring) JNIHandles::make_local(env, result);
JVM_END

and obviously to understand it, you'll have to start digging through the JVM internals. In brief, there is an entity in the native world called StringTable, which keeps references to intern'ed strings, and this method delegates to it. Further explanation is probably beyond the scope of the question, but you can download the JDK sources and inspect them, if you are keen! Good luck!

SusanW
  • 1,550
  • 1
  • 12
  • 22