The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


More printing

As I mentioned in the last chapter, you can put as many statements as you want in main. For example, to print more than one line:

class Hello {

  // main: generate some simple output

  public static void main (String[] args) {
    System.out.println ("Hello, world.");     // print one line
    System.out.println ("How are you?");      // print another
  }
}

Also, as you can see, it is legal to put comments at the end of a line, as well as on a line by themselves.

The phrases that appear in quotation marks are called strings, because they are made up of a sequence (string) of letters. Actually, strings can contain any combination of letters, numbers, punctuation marks, and other special characters.

println is short for "print line," because after each line it adds a special character, called a newline, that causes the cursor to move to the next line of the display. The next time println is invoked, the new text appears on the next line.

Often it is useful to display the output from multiple print statements all on one line. You can do this with the print command:

class Hello {

  // main: generate some simple output

  public static void main (String[] args) {
    System.out.print ("Goodbye, ");
    System.out.println ("cruel world!");
  }
}

In this case the output appears on a single line as Goodbye, cruel world!. Notice that there is a space between the word "Goodbye" and the second quotation mark. This space appears in the output, so it affects the behavior of the program.

Spaces that appear outside of quotation marks generally do not affect the behavior of the program. For example, I could have written:

class Hello {
public static void main (String[] args) {
System.out.print ("Goodbye, ");
System.out.println ("cruel world!");
}
}

This program would compile and run just as well as the original. The breaks at the ends of lines (newlines) do not affect the program's behavior either, so I could have written:

class Hello { public static void main (String[] args) {
System.out.print ("Goodbye, "); System.out.println
("cruel world!");}}

That would work, too, although you have probably noticed that the program is getting harder and harder to read. Newlines and spaces are useful for organizing your program visually, making it easier to read the program and locate syntax errors.



Last Update: 2011-01-24