Chapter -2: Writing Your First Program |
||||
55 views
As you learned during Chapter 1, “Becoming a Programmer,” a computer program is a set of instructions that tell a computer what to do. These instructions are prepared in the same way instructions could be given to a person: You type them into a word processor. However, that’s where the similarity ends. Instructions given to a computer must be written using a programming language. Dozens of computer programming languages have been created; you might have heard of some of them, such as BASIC or Pascal. During this Chapter, you will create your first Java program by entering it using any word processor you like. When that’s done, you will save the program, compile it, and test it out. The following topics will be covered during this hour: * Entering a program into a word processor What You Need to Write Programs:As explained in Chapter 1, to create Java programs, you must have the current version of the Software Development Kit, or another development tool that supports Java 2 version 1.4. You need something that can be used to compile and test Java programs. You also might need a word processor to write programs. With most programming languages, computer programs are written by entering text into a word processor (also called a text editor). Some programming languages, such as Visual C++ from Microsoft, come with their own word processor. Several advanced tools that you could use as an alternative to the Software Development Kit, such as Borland JBuilder and Sun ONE Studio, also come with their own editors. Java programs are simple text files without any special features, such as centered text, boldface text, or other enhancements. They can be written with any word processing program that can create text files. Microsoft Windows systems have several word processors you can use, including Notepad, WordPad, and the DOS program Edit. Apple Macintosh users can create programs with Simple Text, or other editors such as BBEdit Lite. Linux and Unix users can use vi, emacs, and others. Any of these will work fine. You can also use more sophisticated word processors such as Microsoft Word if you remember to save the programs as text. This option has different names depending on the program you are using. In Word, the file should be saved as a file of type Text Only. Other programs call these files DOS text, ASCII text, or something similar. You’ll probably have a better experience creating the programs in this book if you choose a simple word processor to work on source code rather than a sophisticated editing tool such as Word. Note: If you’re in doubt about whether a word processor can save files as text files, you can always use one of the simple programs that come with your operating system. For instance, Windows users can rely on Notepad to create Java programs, because text files created with Notepad are always saved as text-only files. Creating the Saluton Program:The first Java program that you create will be an application that displays a traditional greeting from the world of computer science, “Saluton mondo!” Beginning the Program:Using your word processor, begin your Java programming career by entering each line from Listing 2.1. Don’t enter the line number and colon at the beginning of each line— these are used in this book so that specific line numbers can be referred to. Example 2.1. The Saluton Program1: class Saluton {
2: public static void main(String[] arguments) {
3: // My first Java program goes here
4: }
5: }
Make sure to capitalize everything exactly as shown, and use your spacebar or Tab key to insert the blank spaces in front of some lines. When you’re done, save the file with the file name Saluton.java. At this point, Saluton.java contains the bare-bones form of a Java program. You will create several programs that start off exactly like this one, except for the word Saluton on Line 1. This word represents the name of your program and changes with each program you write. Line 3 should also make sense—it’s a sentence in actual English. The rest is completely new, however, and each part is introduced in the following sections. The class StatementThe first line of the program is the following: class Saluton {
Translated into English, this line means, “Computer, give my Java program the name Saluton.” As you might recall from Chapter 1, each instruction you give a computer is called a statement. The class statement is the way you give your computer program a name. It’s also used to determine other things about the program, as you will see later. The significance of the term class is that Java programs are also called classes. In this example, the program name Saluton matches the file name you gave your document, Saluton.java. As a rule, a Java program should have a name that matches the first part of its filename, and they should be capitalized in the same way. If the program name doesn’t match the filename, you will get an error when you try to compile some Java programs, depending on how the class statement is being used to configure the program. Although some programs can have a filename that doesn’t match its program name, this makes it more difficult to work with the file later on. What the main Statement DoesThe next line of the program is the following: public static void main(String[] arguments) {
This line tells the computer, “The main part of the program begins here.” Java programs are organized into different sections, so there needs to be a way to identify the part of a program that will be handled first. The main statement is the entry point to almost all Java programs. The exception are applets, programs that are run in conjunction with a World Wide Web page. Most of the programs you will write during the next several hours use main as the starting point. Those Squiggly Bracket MarksIn the Saluton program, every line except Line 3 contains a squiggly bracket mark of some kind—either an { or an }. These brackets are a way to group parts of your program (in the same way that parentheses are used in a sentence to group words). Everything between the opening bracket, {, and the closing bracket, }, is part of the same group. These groupings are called blocks. In Listing 2.1, the opening bracket on Line 1 is associated with the closing bracket on Line 5, which makes your entire program a block. You will always use brackets in this way to show the beginning and end of your programs. Blocks can be located inside other blocks (just as parentheses are used here (and a second set is used here)). The Saluton program has brackets on Line 2 and Line 4 that establish another block. This block begins with the main statement. Everything that is inside the main statement’s block is a command for the computer to handle when the program is run. The following statement is the only thing located inside the block: // My first Java program goes here This line is a placeholder. The // at the beginning of the line tells the computer to ignore this line—it is put in the program solely for the benefit of humans who are looking at the program’s text. Lines that serve this purpose are called comments. Right now, you have written a complete Java program. It can be compiled, but if you run it, nothing will happen. The reason is that you have not told the computer to do anything yet. The main statement block contains only a line of comments, which is ignored. If the Saluton program is going to greet anyone, you will have to add some commands inside the opening and closing brackets of the main statement block. Storing Information in a Variable:In the programs you write, one thing that’s often needed is a place to store information for a brief period of time. You can do this by using a variable, a storage place that can hold information such as integers, floating-point numbers, true-false values, characters, and lines of text. The information stored in a variable can change, which is where the name “variable” comes from. Load the Saluton.java file into your word processor (if it’s not already loaded) and replace Line 3 with the following: String greeting = “Saluton mondo!”; This statement tells the computer to store the line of text “Saluton mondo!” into a variable called greeting. In a Java program, you must tell the computer what type of information a variable will hold. In this program, greeting is a string—a line of text that can include letters, numbers, punctuation, and other characters. Putting String in the statement String greeting = “Saluton mondo!”; sets up the variable to hold string values. When you enter this statement into the program, a semicolon must be included at the end of the line. Semicolons are used at the end of each statement in your Java programs. They’re like periods at the end of a sentence; the computer uses them to determine when one statement ends and the next one begins. Displaying the Contents of a Variable: If you ran the program at this point, it wouldn’t display anything. The command to store a line of text in the greeting variable occurs behind the scenes. To make the computer show that it is doing something, you can display the contents of that variable. Insert another blank line in the Saluton program after the String greeting = “Saluton mondo!”; statement. Use that space to enter the following statement: System.out.println(greeting); This statement tells the computer to display the value stored in the greeting variable. The System.out.println statement tells the computer to display a line on the system output device. In this case, the system output device is your computer monitor. Note: If you learned to type on a typewriter rather than a computer, watch out for hitting the “1″ key as an alternative to the “l” key (lowercase “L”). A1though your cerebra1 cortex is perfect1y happy to treat the numera1 as the 1etter when it appears, the computer isn’t as adaptab1e as your brain. Your program won’t compile if you use print1n instead of println, for example Saving the Finished Product:Your program should now resemble Listing 2.2, although you might have used slightly different spacing in Lines 3–4. Make any corrections that are needed and save the file as Saluton.java. Keep in mind that all Java programs are created as text files and are saved with the .java file extension. Example 2.2. The Finished Version of the Saluton Program1: class Saluton {
2: public static void main(String[] arguments) {
3: String greeting = "Saluton mondo!";
4: System.out.println(greeting);
5: }
6: }
When the computer runs this program, it will run each of the statements in the main statement block on Lines 3 and 4. Listing 2.3 shows what the program would look like if it were written in the English language instead of Java. Example 2.3. A Line-by-Line Breakdown of the Saluton Program1: The Saluton program begins here: 2: The main part of the program begins here: 3: Store the text "Saluton mondo!" in a String variable named greeting 4: Display the contents of the variable greeting 5: The main part of the program ends here. 6: The Saluton program ends here. Compiling the Program into a Class File:Before you can try out the program, it must be compiled. The term compile might be unfamiliar to you now, but you will become quite familiar with it in the coming Chapters. When you compile a program, you take the instructions you have given the computer and convert them into a form the computer can better understand. You also make the program run as efficiently as possible. Java programs must be compiled before you can run them. With the Software Development Kit, programs are compiled using the javac program. The javac program, like all programs included with the Software Development Kit, is a command-line utility. You run the program by using your keyboard to type a command at a place that can accept the input. This place is what the term command-line refers to. Because most Linux usage is handled at the command-line, readers with that operating system will be familiar with how the Kit’s programs are used. Anyone who used MS-DOS prior to the introduction of Windows has also used a command line. Many Windows users might not be aware that their operating system includes a command-line feature of its own: the MS-DOS window. To compile the Saluton program using the Software Development Kit, go to a command-line and open the folder on your system where the Saluton.java file is located, then type the following at the command line: javac Saluton.java If the program compiles successfully, a new file called Saluton.class is created in the same folder as Saluton.java. If you have any error messages, refer to the following section, “Fixing Errors.” All Java programs are compiled into class files, which are given the .class file extension. A Java program can be made up of several classes that work together, but in a simple program such as Saluton only one class is needed. If errors exist in your program when you compile it, a message is displayed that explains each error and the line on which it occurred. The following output illustrates an attempt to compile a program that has an error, and the error messages that is displayed as a result: C:\J24Work>javac Saluton.java
Saluton.java:4: cannot resolve symbol.
symbol : method print1n (java.lang.String)
location: class java.io.PrintStream
System.out.print1n(greeting);
^
1 error
C:\J24Work>
Error messages displayed by the javac tool include the following information:
As you learned during the past hour, errors in programs are called bugs. Finding those errors and squashing them is called debugging. The following is another example of an error message you might see when compiling the Saluton program: Saluton.java:4: cannot resolve symbol.
symbol : variable greting
location: class Saluton
System.out.println(greting);
^
In this example, the 4 that follows the file name Saluton.java indicates that the error is on Line 4. This is where having a line-numbering word processor comes in handy—you can jump more easily to the Java statement that’s associated with the error. The actual error message, cannot resolve symbol in this case, can often be confusing to new programmers. In some cases, the message can be confusing to any programmer. When the error message doesn’t make sense to you, take a look at the line where the error occurred. For instance, can you determine what’s wrong with the following statement? System.out.print1n(greting); The problem is that there’s a typo in the variable name, which should be greeting instead of greting. If you get error messages when compiling the Saluton program, double-check that your program matches Listing 2.2, and correct any differences you find. Make sure that everything is capitalized correctly, and that all punctuation marks (such as {, }, and ; ) are included. Often, a close look at the statement included with the error message is enough to reveal the error, or errors, that need to be fixed. Workshop: Running a Java Program:To run the Java program you have just created, you must use a Java interpreter such as java, the command-line tool included with the Software Development Kit. An interpreter makes the computer follow the instructions you gave it when you wrote the program. To run a Java program, the command java is followed by a space and the name of the class file that contains the program. Although the class file’s name includes the .class extension, this part of the name must be left off when running the program with the Java interpreter. To see whether the Saluton program does what you want, run the class. If you’re using the kit, go to the folder that contains the Saluton.class file, and type the following at a command line: java Saluton Even though the program’s filename is Saluton.class, you don’t include the file extension .class in the command. When the program runs, it should state the following: Saluton mondo! If you see this text, you have just written your first working Java program. Your computer has just greeted the world, a tradition in the field of computer programming that’s as important to many of us as caffeine, short-sleeved dress shirts, and the Star Wars films. You may be asking yourself why “Saluton mondo!” is a traditional greeting, especially if you have tried using it in a conversation with other programmers and received funny looks in response. It’s the phrase “Hello world!” in Esperanto, an artificial language created by Ludwig Zamenhof in 1887 to facilitate international communication. The author uses it here in the hope that more computers will be inspired to learn Esperanto. Summary:During this Chapter, you got your first chance to create a Java program. You learned that to develop a Java program you need to complete these three basic steps: 1. Write the program with a word processor. Along the way, you were introduced to some basic computer programming concepts such as compilers, interpreters, blocks, statements, and variables. These things will become clearer to you in successive hours. As long as you got the Saluton program to work during this Chapter, you’re ready to proceed. Q&A:
Quiz:Test your knowledge of the material covered in this chapter by answering the following questions. Questions
Answers
Activities:If you’d like to explore the topics covered in this hour a little more fully, try the following activities: * You can translate the English phrase “Hello world!” into other languages using the AltaVista Web site Babelfish, located at http://babel.altavista.com. Write a program that enables your computer to greet the world in a language such as French, Italian, or Portuguese. |
| « Chapter -1: Becoming a Programmer | Chapter - 3: Vacationing in Java » |
| Posted on Tuesday, January 27th, 2009 at 7:00 pm under Java 2 (simpler way-Old version) | RSS 2.0 Feed | |