Understanding Java's System.out.println(): Internals, Overloading, and OOP Principles
This article explains the inner workings of Java's System.out.println() method, covering the System and out components, the PrintStream class, method overloading, and example code demonstrating how different argument types affect output, thereby illustrating core object‑oriented programming concepts.
Last fall recruitment interview I was asked: how do you understand System.out.println() ?
Having studied object‑oriented programming for a long time, how can we express it in a single line of code?
If you can read and understand System.out.println() , you truly grasp the meaning of Java object‑oriented programming.
Object‑oriented programming creates objects, and lets objects do the work (i.e., objects invoke methods).
System.out.println("hello world"); hello world
Process finished with exit code 0First, analyze the System source.
System is a custom class defined by Java.
Analysis of the out field.
① out is a static data member inside System, holding a reference to the java.io.PrintStream class.
② Because out is static, it can be accessed directly via the class name and field name: System.out .
Analysis of println.
① println() is a method in the java.io.PrintStream class that outputs information to the console.
② The method has many overloads, allowing virtually any type of data to be printed.
In short: a class calls an object, and the object calls a method.
Extended Knowledge Points:
1. Difference between System.out.print() and System.out.println()
2. Character array output interview case
public class Demo {
public static void main(String[] args) {
char[] ch = new char[]{'x','y'};
System.out.println(ch);
char[] ch1 = new char[]{'x','y'};
System.out.println("ch1="+ch1);
}
} xy
ch1=[C@74a14482This demonstrates the overload of println() ; Java automatically calls the argument's toString() method when printing.
The parameters of println are of basic types: one is String, the other is Object.
System.out.println(ch) invokes println(char[]) , which is treated as an Object type, so the output is xy .
However, System.out.println("ch="+ch) uses the string concatenation operator + , which calls println(String) ; the result is a string like xxx@xxxx (the default toString() representation of the char array).
Source: cnblogs.com/blessing2022/p/16622118.html
Recommended Reading: Complete Java interview question bank
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.