Java Examples Explained

Home » 3. Input and Output » 3.2. Standard Output

Category Archives: 3.2. Standard Output

Hello world!

This is a classic first program example used in teaching any programming languages. What it does is pretty boring, which is just displaying the sentence “Hello World” on the screen. However, it is your first step and crucial for your understanding in Java. Here is the program:


1|public class HelloWorld 
2|{ 
3|    public static void main(String[] args) 
4|    { 
5|        System.out.println("Hello World.");
6|    } 
7|}
	

And this is what you see on the screen after you compiled and run the program:

Hello World.

The one statement that instructs the computer to display the sentence “Hello World” to your screen is on line 5. You can change the sentence to anything you like, as long as the sentence is between the two double quotes (“). But make sure you don’t change anything else. Simple, right?

So, what does all the other lines of statement do? Well, a simple way of looking at it, they form the basic skeleton of a Java program. Which means, if you want to make sure that your Java program runs, you must have them. Written exactly like that? If you are a beginner, the answer is yes, except for the last word on line 1. HelloWorld is the name given to your program. You can change it to any other name you like, but you have to make sure that it is the same as the name of your program file, and must be spelt exactly the same where capital and small letters are concerned.

There are however restrictions of how you can name your program, and you can follow the same rules applied to variables naming.

HelloWorld in this example is actually the class name of your program. A Java program must contain at least one class, which in this case is HelloWorld. Therefore, line 1 is basically introducing the HelloWorld class. The open curly bracket ({) on line 2 marks the beginning of the class, and the close curly bracket (}) on line 7 marks the end of the class.

Each Java program starts from the main method, and this is where you write statements or instructions that you would like the program to do. The main method must be placed within a class. Can you spot the main method in the above code? Yes, line 3 introduces the main method, and curly brackets on line 4 and 6 marks the beginning and end of the main method, respectively. If you notice, curly brackets are symbols used to mark the beginning and end of a certain segment or block in Java.

Notice the words publicclass, and void in line 1 and 3. These are keywords in Java. This means that these words have special meanings and can only be used in certain ways. Incorrect use of these words can cause errors. There are many more keywords in Java that you will come across in other examples. For now, it is enough to understand that this is how you use these keywords to introduce the class name (line 1) and main method (line 3). main is a special keyword used for the main method, and only used for this purpose.

Just like any other programming languages, a library of functions or tools are provided for Java programmers. In Java, we call them pre-defined classes. You can use these classes to do certain tasks within your own Java programs. In this example, we use two pre-defined classes: System and String

System provides facilities to receive input and display output in your program. As you can see in line 5, it is used to display “Hello World” on the standard output, which is your computer screen. There are many ways of using System to display output as you will see in other examples. We don’t actually use String to do anything in this example, but we need it for the main method introduction.

You might wonder why line 3,4, and 6 are written with extra spaces on the left, and line 5 is further to the right. Is it necessary? No. If you like, you can write all the 7 lines in one. It will produce the same output, as long as the order is correct. So why the indentation? Well, it is a good programming practice, and highly recommended. It makes it easy for you to read, detect the beginning and end of a block, and check whether your blocks are nested correctly.

Let’s look back at the output of this program. Notice that the sentence displayed does not contain double quotes. So, how do you display a sentence containing double quotes? Can you add double quotes within double quotes? No. If you do this, you might get some error messages, or your program behaves unexpectedly. This will be discussed and explained in the next example, Famous Quotes.

If you find this way of displaying output rather dull and boring, have a look at Hello World (GUI) which ‎produces the output in a dialog box.

Famous Quotes

Let’s say we want to display a famous quote by Robert Frost in the following way:


"Two roads diverged in a wood, and I --
 I took the one less traveled by, 
 and that has made all the difference."
				~Robert Frost

There are two things we want to achieve here, display the double quotes (“), and display Robert Frost to the far right.

The program below shows one way to do it:

1|public class FrostQuote { 
2|   public static void main(String[] args) { 
3|      System.out.print("\"Two roads diverged in a wood, ");
4|	System.out.println("and I --");
5|	System.out.print(" I took the one less traveled by, \n");
6|	System.out.println(" and that has made all the difference.\"");
7|	System.out.println("\t\t\t\t~Robert Frost");
8|   } 
9|}
	

On the first line of Robert Frost’s quote, we have a (“) before the word ‘Two’. In order to display this symbol, we have to add a backslash symbol (\) as shown on line 3. Why? Remember that println() method will print anything you put within two (“)s. So the first (“) will mark the beginning of the sentence you want to print, and it will print anything until it finds the next (“) that marks the end of the sentence. So, if on line 3, you don’t add the (\), the (“) you add before the word ‘Two’ will be assumed as the mark of end of sentence. And the rest of the sentence after the (“) does not follow the proper format of println() method, therefore will produce an error. By adding the (\), it differentiates the following (“) from the (“) marking the end of sentence, and therefore will be printed as it is. We use the same symbol on line 6 to print the (“) after end of Robert Frost’s quote.

Now, we look at how we make Robert Frost printed further to the right of the screen. If we are using a word processor, what we do is just press the tab key a few times. Well, here we use similar concept actually, by using a control character that have the same effect as pressing a tab key, which is backslash and ‘t’ (\t). As you can see on line 7, we use (\t) 4 times to mimic the effect of pressing tab keys 4 times.

You may notice that in this example we use two methods to display our sentences, print() and println(). What is the difference between the two? As you might have guessed, println() method will display the sentence between two (“) on one line, and then move the cursor to the next line and ready for the next instruction. On the other hand, print() method will stay on the same line after displaying the sentence. That is why line 3 and 4 of the code produce the first line of Robert Frost’s quote.

What about the print() method on line 5? Why do you think it has the same effect as using println() method? Because in there, we have another control character, backslash and ‘n’ (\n), which is also known as newline character. It has the same effect as pressing return or enter key, which moves the cursor to a new line. So even though print() does not move your cursor to the next line, the newline character (\n) does.

There are a few other control characters that allow you display your sentences the way you like it, but the most popular ones are (\n) and (\t).

The previous example and this example show us how to display sentences using print() and println(). In order to change the sentences, we have to modify the program, recompile and run it again. Otherwise, every time we run the program, it will produce the same output. So, how do we make our program more flexible, and allow us change certain things without modifying the program and recompiling it? The next example, Customised Hello will show you how.

You could also have a look at the GUI version of this program at Famous Quotes (GUI)‎.