Compared to some languages, you might find writing out basic output in Java…well…overly complex. However, once you understand Java, you will see that it is complex, but for a reason.
Let’s first consider some languages you might have already seen.
print("Hello World") # Python
printf("Hello World"); /* C */
cout << "Hello World" << endl; // C++
Each one of these prints “Hello World” to your console window. So how does Java do it?
System.out.println("Hello World");
Compared to print()
or cout
, that might seem like a lot to do.
(Almost) Everything is an Object
The key thing to remember is that Java was built from the ground up as an object oriented language. So while it relies heavily upon C++ for it’s structure, it is its own language. One of the key things about Java is that almost everything is an object, and you will need to reference those objects and their methods to work with them.
When you write a Java application, you get several objects readily available to you.
System
is one of them. If you were to go poking around System, you would find it has a wide array of system level details you can access. (System is anything dealing with your local computer system if you were wondering.)
One of the things you can work with is the output object, called out
. This is the basic, system level console output tool, and shouldn’t be confused with other types of output such are outputting something to a printer, or and error log, or any other output actually.
So when you call System.out, you are specifying that you need a system level object, and you want to use the console out object for it.
If you notice, you start with something large (System
) and work your way down to something more specific (out
).
However, you only now are working with the out
object, and object don’t do things without calling their methods. out
has several methods you can use, including most notably print()
and println()
.
Both are overloaded methods so you can pass Strings or primitive data to them to print out. However, you cannot mix data types.
The difference between the two is print()
prints the data to the current line. println()
prints the data to the current line, and then prints a new line so the next piece of information to print goes on a new line.
Console Output in Java was originally found on Access 2 Learn