Small Java Programs

This chapter discusses naming and coding conventions as well as reserved words in Java. When you go through this chapter, you'll get some hands-on experience with writing in Java.

5. println()


public    static void main(String[]  args   )

The Java compiler would accept the line. But it looks sloppy to human eyes.


public class Hello
  public static void main ( String[] args )
    System.out.println("Hello World!");

There are rules about where spaces may be used, and optional style rules about how to make a program look nice. Rather than look at a list of rules, look at some Java programs and pick up the rules by example.

The main method of this program consists of a single statement:

System.out.println("Hello World!");

This statement writes the characters inside the quotation marks on one line. (The quotation marks are not written.)

statement in a programming language is a command for the computer to do something. It is like a sentence of the language. A statement in Java is followed by a semicolon.

Methods are built out of statements. The statements in a method are placed between braces { and } as in this example.

Programs usually contain many methods. Our example program contains just one method.

The part "Hello World!" is called a string literal. A string is a sequence of characters. A string literal consists of characters between quote marks, but does not include the quote marks. It can contain any valid character, including white space and punctuation. This program writes a string to the monitor and then stops.

In a source file, a string literal must be on just one line. The following is not legal, and will not compile:


Question 5:

(Review: ) Say that the file contains the example program. In order to run it, what
two things must be done?