I've been learning java programming recently and I am quite confused between these two statements.
System.out.println("Hello, world");
System.console().printf("Hello, world");
I know that out
is a static
variable of System
class and printf()
is the method of Printstream
class.
But I am not getting the second statement. I know a little bit of OOP . So if System
class has a method like console()
then how can a method have methods like printf()
?
The console()
method doesn't have a method like printf()
, it returns an object that has a printf()
method. Specifically, the console()
method returns a Console
object.
This pattern is called method chaining .
So if
System
class has a method likeconsole()
then how can a method have methods likeprintf()
?
System.console()
returns a Console
object, and you're invoking the printf()
method on that Console
object.
The console()
method returns an instance of Console
object.
You can rewrite it like this:
Console console = System.console();
console.printf("Hello, world");
See https://docs.oracle.com/javase/7/docs/api/java/io/Console.html for more details
From System javadoc :
console()
Returns the unique Console object associated with the current Java virtual machine, if any.
So console() method returns a Console object and printf()
is a method of class Console
System.out.println()
on the other hand is calling println()
method on the static PrintStream field "out" of class System
Java statements and method calls are evaluated left to right. System has a method console() which grants access to the console associate with the JVM. You are now working the object representing the console of the JVM when you call the method printf(). printf() is a method of the console of the JVM, not System itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.