Printing in Java
Writing Hello World
Writing a program that prints "Hello world" to the console requires a few lines of code:
public class HelloWorld
{
public static void main(String[] Args)
{
System.out.println("Hello world");
}
}
There are a few key parts to pay attention to here:
- The method
public static void main(String[] Args)
is special method in java. It is always the first method that will be called to start a java program there should only be one main method per program. - The text is printed to the console with the
System.out.println()
command. This command looks a bit long, but you can think of it as telling the console to print whatever is inside the parentheses.
Now that you can print to the console, you'll be able to write programs that can display information to the user!
print() vs println()
In java you can use System.out.println()
and System.out.println()
commands multiple times in your programs.
System.out.println()
always prints a new line character at the end of a string so then next item ot be printed will be on the next line. The following code:public class PrintTester { public static void main(String[] Args) { System.out.println("Line #1"); System.out.println("Line #2"); } }
will output the following
Line #1 Line #2
System.out.print()
does not insert a new line after printing. This is helpful when printing prompts for user input, or while printing items using a loop.public class PrintTester2 { public static void main(String[] Args) { System.out.print("This is "); System.out.print("Cool!"); } }
will output the following
This is Cool!