Hello World

1
2
3
4
5
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
}
}

invokevirtual
$ javap -c HelloWorld

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Compiled from "HelloWorld.java"
public class HelloWorld {
public HelloWorld();
Code:
0: aload_0
// Method java/lang/Object."<init>":()V
1: invokespecial #1
4: return

public static void main(java.lang.String[]);
Code:
// Field java/lang/System.out:Ljava/io/PrintStream;
0: getstatic #2
// String hello world
3: ldc #3
// Method java/io/PrintStream.println:(Ljava/lang/String;)V
5: invokevirtual #4
8: return
}

The property out in System is a packaged type PrintStream.
There is a BufferedOutputStream inside PrintStream.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public final class System {
...
public final static PrintStream out = null;
...
private static native void setOut0(PrintStream out);
...
private static void initializeSystemClass() {
...
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
...
setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
...
}
}

The init method called after thread initialization, initialize the system class.


1
2
3
4
5
6
7
8
private static PrintStream newPrintStream(FileOutputStream fos, String enc) {
if (enc != null) {
try {
return new PrintStream(new BufferedOutputStream(fos, 128), true, enc);
} catch (UnsupportedEncodingException uee) {}
}
return new PrintStream(new BufferedOutputStream(fos, 128), true);
}

package buffer function into out. base on encoding, create output stream object.



1
2
3
4
5
6
7
8
9
JNIEXPORT void JNICALL
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
{
jfieldID fid =
(*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");
if (fid == 0)
return;
(*env)->SetStaticObjectField(env,cla,fid,stream);
}

  • The native method setOut0 will call this c function.

  • fid the member of System the out‘s id.

  • "Ljava/io/PrintStream;" mean java.io.PrintStream object

SetStaticObjectField define here.

1
2
void (JNICALL *SetStaticObjectField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value);