1.1   Your First Java Program:   Hello World


In this section, our plan is to lead you into the world of Java programming by taking you through the three basic steps required to get a simple program running. The Java system is a collection of applications not unlike any of the other applications that you are accustomed to using (such as your word processor, e-mail program, or internet browser). As with any application, you need to be sure that Java is properly installed on your computer. You also need an editor and a terminal application. Here are system specific instructions for three popular home operating systems. [ Mac OS X · Windows · Linux ]

Programming in Java.

We break the process of programming in Java into three steps:
  1. Create the program by typing it into a text editor and saving it to a file named, say, MyProgram.java.
  2. Compile it by typing "javac MyProgram.java" in the terminal window.
  3. Run (or execute) it by typing "java MyProgram" in the terminal window.

The first step creates the program; the second translates it into a language more suitable for machine execution (and puts the result in a file named MyProgram.class); the third actually runs the program.

Errors.

Most errors are easily fixed by carefully examining the program as we create it, in just the same way as we fix spelling and grammatical errors when we type an e-mail message. One of the very first skills that you will learn is to identify errors; one of the next will be to be sufficiently careful when coding to avoid many of them.

Input and output.

Typically, we want to provide input to our programs: data that they can process to produce a result. The simplest way to provide input data is illustrated in UseArgument.java. Whenever this program is executed, it reads the command-line argument that you type after the program name and prints it back out to the terminal as part of the message.
% javac UseArgument.java
% java UseArgument Alice
Hi, Alice. How are you?
% java UseArgument Bob
Hi, Bob. How are you?

Q + A

Q. Why Java?

A. The programs that we are writing are very similar to their counterparts in several other languages, so our choice of language is not crucial. We use Java because it is widely available, embraces a full set of modern abstractions, and has a variety of automatic checks for mistakes in programs, so it is suitable for learning to program. There is no perfect language, and you certainly will be programming in other languages in the future.

Q. Do I really have to type in the programs in the book to try them out?

A. Everyone should type in HelloWorld.java, but you can find all of the code in this book (and much more) on this booksite.

Q. What are Java's rules regarding tabs, spaces and newline characters?

A. There are not many. Java compilers treat them all to be equivalent. For example, we could also write HelloWorld as follows:

public class HelloWorld { public static void main ( 
String [] args) { System.out.println("Hello World") ; } }
But we do normally adhere to spacing and indenting conventions when we write Java programs, just as we always indent paragraphs and lines consistently when we write prose or poetry.

Q. What are the rules regarding quotation marks?

A. Material inside quotation marks is an exception to the rule of the previous question: things within quotes are taken literally so that you can precisely specify what gets printed. If you put any number of successive spaces within the quotes, you get that number of spaces in the output. If you accidentally omit a quotation mark, the compiler may get very confused, because it needs that mark to distinguish between characters in the string and other parts of the program. To print a quotation mark, a newline, or a tab, use \", \n, or \t, respectively, within the quotation marks.

Q. What is the meaning of the words public, static and void?

A. These keywords specify certain properties of main() that you will learn about later in the book. For the moment, we just include these keywords in the code (because they are required) but do not refer to them in the text.

Q. What happens when you omit a brace or misspell one of the words, like public or static or main? A. It depends upon precisely what you do. Such errors are called syntax errors. Try it out and see.

Q. Can a program use more than one command-line argument?

A. Yes, you can put several, though we normally use only a few. You refer to the second one as args[1], the third one as args[2], and so forth. Note that we start counting from 0 in Java.

Q. What Java systems libraries and methods are available for me to use?

A. There are thousands of them, but we introduce them to you in a deliberate fashion in this book to avoid overwhelming you with choices.

Q. How should I format my code? How should I comment my code?

A. Programmers use coding guidelines to make programs easier to read, understand, and maintain. As you gain experience, you will develop a coding style, just as you develop style when writing prose. Appendix B provides some guidelines for formatting and commenting your code. We recommend returning to this appendix after you've written a few programs.

Q. What exactly is a .class file?

A. It's a binary file (sequence of 0s and 1s). If you are using Unix or OS X, you can examine its contents by typing od -x HelloWorld.class at the command prompt. This displays the results in hexadecimal (base 16). In deference to Java's name, the first word of every .class file is cafe.

Exercises

  1. Write a program TenHelloWorlds.java that prints "Hello, World" ten times.
  2. Describe what happens if, in HelloWorld.java, you omit
    1. public
    2. static
    3. void
    4. args
  3. Describe what happens if, in HelloWorld.java, you misspell (by, say, omitting the second letter)
    1. public
    2. static
    3. void
    4. args
  4. Describe what happens if you try to execute Hi.java with:
    1. java Hi
    2. java Hi @!&^%
    3. java Hi 1234
    4. java Hi.class Bob
    5. java Hi.java Bob
    6. java Hi Alice Bob
  5. Modify UseArgument.java to make a program UseThree.java that takes three names and prints out a proper sentence with the names in the reverse of the order given, so that for example, "java UseThree Alice Bob Carol" gives "Hi Carol, Bob, and Alice.".

Web Exercises

  1. Write a program Initials.java that prints your initials using nine rows of asterisks like the one below.
    **        ***    **********      **             *             **
    **      ***      **        **     **           ***           **
    **    ***        **         **     **         ** **         **
    **  ***          **          **     **       **   **       **
    *****            **          **      **     **     **     **
    **  ***          **          **       **   **       **   **
    **    ***        **         **         ** **         ** **
    **      ***      **        **           ***           ***
    **        ***    **********              *             *
    

  2. Describe what happens if, in HelloWorld.java, you omit
    1. main
    2. String
    3. HelloWorld
    4. System.out
    5. println
  3. Describe what happens if, in HelloWorld.java, you omit
    1. the ;
    2. the first "
    3. the second "
    4. the first {
    5. the second {
    6. the first }
    7. the second }
  4. Describe what happens if, in HelloWorld.java, you misspell (by, say, omitting the second letter)
    1. main
    2. String
    3. HelloWorld
    4. System.out
    5. println
  5. I typed in the following program. It compiles fine, but when I execute it, I get the error java.lang.NoSuchMethodError: main. What am I doing wrong?
    public class Hello {
       public static void main() {
          System.out.println("Doesn't execute");   
       }
    }
    
    Answer: you forgot the String[] args. It is required.