search
HomeJavajavaTutorialAnalysis of HelloWorld principle in Java

The first program we use when learning Java is "hello world". The following is an analysis of the principles of Java HelloWorld through example code. Friends who are interested can learn together.

The first program for us to learn Java is "hello world"

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

What is the above program? What about outputting "hello world" on the screen? This is what was originally intended to be explained, that is, the principle of System.out.println("hello world").

Let’s first look at the process of System.out.println. Let’s first look at the definition of out in System.java. The source code is as follows:

public final class System {
   ... 
   public final static PrintStream out = null; 
   ...
 }

From it, we find that

(01) out is static## of System.java #variable.

(02) And out is a PrintStream

object, and there are many overloaded println() methods in PrintStream.java.

OK, we know that out is a PrintStream object. Next, see how it is initialized and how it is related to screen output?

Let’s analyze it step by step. First, look at the initializeSystemClass() method of System.java.

1. The source code of initializeSystemClass() is as follows: Mark the out part in red

 private static void initializeSystemClass() {
   props = new Properties();
   initProperties(props); // initialized by the VM
   sun.misc.VM.saveAndRemoveProperties(props);
   lineSeparator = props.getProperty("line.separator");
   sun.misc.Version.init();
   FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
   FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
   FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
   setIn(new BufferedInputStream(fdIn));
   setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
   setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
   loadLibrary("zip");
   Terminator.setup();
   sun.misc.VM.initializeOSEnvironment();
   Thread current = Thread.currentThread();
   current.getThreadGroup().add(current);
   setJavaLangAccess();
   sun.misc.VM.booted();
 }

We only need to pay attention to the red code part above:

FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));

Change these two sentences If subdivided, it can be divided into the following steps:

Step 1 FileDescriptor fd = FileDescriptor.out;

Step 2 FileOutputStream fdOut = new FileOutputStream(fd);

Step 3 BufferedOutputStream bufOut = new BufferedOutputStream(fdOut, 128);

Step 4 PrintStream ps = new PrintStream(bufout, true);

Step 5 setOut0(ps);

Instructions:

(01) Step 1, get the static member out in FileDescriptor.java. out is a FileDescriptor object, which is actually the identifier of "standard output (screen)" .


The code related to FileDescriptor.out in FileDescriptor.java is as follows:

 public final class FileDescriptor {
    private int fd;
   public static final FileDescriptor out = new FileDescriptor(1);
   private FileDescriptor(int fd) {
     this.fd = fd;
     useCount = new AtomicInteger();
   }
   ...
 }

(02) Create a "File Output Stream" corresponding to "Standard Output (Screen)".

(03) Create a "buffered output stream" corresponding to the "file output stream". The purpose is to add "buffering" functionality to the "File Output Stream".

(04) Create a "print output stream" corresponding to the "buffered output stream". The purpose is to provide a convenient printing

interface for the "buffered output stream", such as print(), println(), printf(); so that it can print output conveniently and quickly.

(05) Execute setOut0(ps);

Next, parse the setOut0(ps) in step 5. Check the declaration of setOut0() in System.java, as follows:

private static native void setOut0(PrintStream out);

From it, we find that setOut0() is a native local method. Through openjdk, we can find its corresponding source code, as follows:

 JNIEXPORT void JNICALL
 Java_java_lang_System_setOut(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);
 }

Description:

This is a JNI

function, let’s do a simple analysis of it.

(01) Function name

JNIEXPORT void JNICALL Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)

This is the static registration method of JNI. Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream) will be the same as setOut0(PrintStream out) in System.java Association; moreover, the parameter stream corresponds to the parameter out. To put it simply, when we call setOut0(), we actually call Java_java_lang_System_setOut0().

(02) jfieldID fid = (*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");

The function of this sentence It is to obtain the jfieldID of the static member out of System.java. "Ljava/io/PrintStream;" means that out is a java.io.PrintStream object.

The purpose of obtaining out's jfieldID is that we need to change the value of out by operating "out's jfieldID".

(03) (*env)->SetStaticObjectField(env,cla,fid,stream);

The function of this sentence is to set the corresponding fid (fid is the jfieldID of out) The value of the static member is stream.

stream is the parameter we pass to Java_java_lang_System_setOut0(), which is the parameter passed to setOut0.

Summary of the above. We know that the function of setOut0(PrintStream ps) is to set ps to the out static variable of System.java.


As mentioned before, FileDescriptor.out is the file identifier of the machine's "standard output (screen)". We can generally understand the file identifier as the "standard output" represented by FileDescriptor.out.

Therefore, in initializeSystemClass(), the above 5 steps are to encapsulate "FileDescriptor.out". The encapsulated System.in has both buffering function and convenient operation interfaces, such as print(), println(), and printf().


The above is the detailed content of Analysis of HelloWorld principle in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor