Compute and Output
Learn how to display data on the computer screen.
The built-in print()
method
Let’s start building the project using built-in methods. We’ve already seen some built-in methods, and we know that a method does the following things:
It takes something as its input.
It processes this input to create some output.
It returns the output.
The most prominent Java built-in method that prints something on the screen is print
. It prints anything we give as input on the screen. But this method belongs to a class called System.out
, meaning we must write System.out.print()
to call this method. For instance, guess the result of the following code when we press the “Run” button.
public class MyJavaApp {public static void main(String[] args) {System.out.print(3.1415);}}
It simply prints the exact number we gave as input to the print
method. As a programmer, this method gives us the power to verify what the computer has done for us. For example, we know what the built-in method round
is supposed to do. It takes any number with a decimal point and rounds it to the nearest whole number, meaning 3.1415 should get rounded to 3. Try it yourself by pressing the “Run” button:
public class MyJavaApp {public static void main(String[] args) {Math.round(3.1415);}}
There wasn’t any error, and the computer seems to have done its job, but we couldn’t really confirm if the round
method worked as we expected. So, what happens if we use print
and round
together? We know by now that a method can take an input, do something with it, and return a processed output. The method named round()
can take as input 3.1415
, process it to truncate the number to the nearest whole number, and then return the whole number 3
. Is there a way for us to take all of what round
as a method does and give that as input to ...