Printing variables to the console
We previously looked at a line of code like this:
System.out.println("Hello World");
It prints the line of Hello World to the screen. If we change the string inside to Greg Heffley, it will print out Greg Heffley.
From now on, we will be writing all our code inside the main method. If we don't, the lesson will clearly say where you should be writing your code.
Let's this a few steps further. Let's create some variables and see how they are printed.
String name = "Rowley Jefferson";
int age = 14;
double pi = 3.14159265;
char ch = 'Z';
boolean isAdult = false;
System.out.println(name);
System.out.println(age);
System.out.println(pi);
System.out.println(ch);
System.out.println(isAdult);
The output for the console looks like this:
Rowley Jefferson
14
3.14159265
Z
false
There are a few things to notice here:
- We can print all primitive types
- We can use variables instead of directly writing the value
- When multiple
printlns are used, they stack
This is important to know, or else your code would be very messy and inefficient.
We have used System.out.println so far, but did you know there is a System.out.print as well? Let's see what happens if we use our previous example without println and with print instead.
System.out.print(name);
System.out.print(age);
System.out.print(pi);
System.out.print(ch);
System.out.print(isAdult);
Here's the output:
Rowley Jefferson143.14159265Zfalse
And there's the main difference: There aren't any line breaks! print differs from println in that it doesn't print content on new lines, but the same line.
Try playing around with a mixture of both print and println.
System.out.println(name);
System.out.print(age);
System.out.println(pi);
System.out.print(ch);
System.out.print(isAdult);