Learn how to print values to the console using Java!
Often when creating programs, we want to display information or data to users so that they are able to understand and use that information.
In Java, the easiest way to display information to a user is by using System.out.println
. System.out.println
is used to display a variety of data types - like Strings, integers, and objects - to the terminal console. To use System.out.println
, we can simply include the value or variable we’d like displayed to the console as a parameter in the print function:
Writing this program in a Java file requires a few additional lines of code:
There are a few key parts to pay attention to here:
The code that we want to execute is written inside a function called main
. Java always looks to the main
function as a place to start the program execution.
The main
function always has this header:
The main
method exists inside of something called a class. A class is a file that can be executed by Java and run in a Java Virtual Machine. The class should encompass all other code in the file.
Try printing out your name and where you live!
When using the System
class, there are two different ways that we can print output: println
and print
. The big difference between these two is that println
will display the message on a new line, while the print
statement will print the message on the same line.
When two println
statements are used together,
the result is:
When two print
statements are used
the result is:
When println
is called twice, the output is displayed on two separate lines. The print
statement, however, displays the output on the same line.
If you were to use println
followed by print
, the print
statement will appear on the next line, but if the print
statement comes before the println
, the statement will stay on the same line.
Take a look at this example:
An easy way of thinking about this, is that println
affects the subsequent line, not the ones that comes before it!
Print your full name to the console using at least 2 print
statements and 1 println
statement.