First Program in Java: Printing a Line of Text

First Program in Java Printing a Line of Text

Every time you use a computer, you execute various applications that perform tasks for you. For example, your e-mail application helps you send and receive e-mail, and your Web browser lets you view Web pages from Web sites around the world. Computer programmers create such applications by writing computer programs.

A Java application is a computer program that executes when you use the java command to launch the Java Virtual Machine (JVM). Let us consider a simple application that displays a line of text. (Later in this section we will discuss how to compile and run an application.) The program and its output are shown in Fig. 2.1. The output appears in the light blue box at the end of the program. The program illustrates several important Java language features. Java uses notations that may look strange to nonprogrammers. In addition, for your convenience, each program we present in this book includes line numbers, which are not part of actual Java programs. We will soon see that line 9 does the real work of the programnamely, displaying the phrase Welcome to Java Programming! on the screen. We now consider each line of the program in order.

Figure 2.1. Text-printing program.

(This item is displayed on page 37 in the print version)

 1 // Fig. 2.1: Welcome1.java
 2 // Text-printing program.
 3
 4 public class Welcome1
 5 {
 6 // main method begins execution of Java application
 7 public static void main( String args[] )
 8 {
 9 System.out.println( "Welcome to Java Programming!" );
10
11 } // end method main
12
13 } // end class Welcome1
 
Welcome to Java Programming!
 

Line 1

 // Fig. 2.1: Welcome1.java

begins with //, indicating that the remainder of the line is a comment. Programmers insert comments to document programs and improve their readability. This helps other people to read and understand programs. The Java compiler ignores comments, so they do not cause the computer to perform any action when the program is run. We begin every program with a comment indicating the figure number and file name.

A comment that begins with // is called an end-of-line (or single-line) comment, because the comment terminates at the end of the line on which it appears. A // comment also can begin in the middle of a line and continue until the end of that line (as in lines 11 and 13).

Traditional comments (also called multiple-line comments), such as

 /* This is a traditional
 comment. It can be
 split over many lines */

can be spread over several lines . This type of comment begins with the delimiter /* and ends with */. All text between the delimiters is ignored by the compiler. Java incorporated traditional comments and end-of-line comments from the C and C++ programming languages, respectively. In this book, we use end-of-line comments.

Java also provides Javadoc comments that are delimited by /** and */. As with traditional comments, all text between the Javadoc comment delimiters is ignored by the compiler. Javadoc comments enable programmers to embed program documentation directly in their programs. Such comments are the preferred Java commenting format in industry. The javadoc utility program (part of the J2SE Development Kit) reads Javadoc comments and uses them to prepare your program's documentation in HTML format. We demonstrate Javadoc comments and the javadoc utility in Appendix H. For complete information, visit Sun's javadoc Tool Home Page at java.sun.com/j2se/javadoc.

Common Programming Error 2.1

Forgetting one of the delimiters of a traditional or Javadoc comment is a syntax error. The syntax of a programming language specifies the rules for creating a proper program in that language. A syntax error occurs when the compiler encounters code that violates Java's language rules (i.e., its syntax). In this case, the compiler does not produce a .class file. Instead, the compiler issues an error message to help the programmer identify and fix the incorrect code. Syntax errors are also called compiler errors, compile-time errors or compilation errors, because the compiler detects them during the compilation phase. You will be unable to execute your program until you correct all the syntax errors in it.

Line 2

 // Text-printing program.

is an end-of-line comment that describes the purpose of the program.

Good Programming Practice 2.1

Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program was last modified. (We are not showing the author, date and time in this book's programs because this information would be redundant.)

Line 3 is simply a blank line. Programmers use blank lines and space characters to make programs easier to read. Together, blank lines, space characters and tab characters are known as white space. (Space characters and tabs are known specifically as white-space characters.) White space is ignored by the compiler. In this chapter and the next several chapters, we discuss conventions for using white space to enhance program readability.

Good Programming Practice 2.2

Use blank lines and space characters to enhance program readability.

Line 4

 public class Welcome1

begins a class declaration for class Welcome1. Every program in Java consists of at least one class declaration that is defined by youthe programmer. These are known as programmer-defined classes or user-defined classes. The class keyword introduces a class declaration in Java and is immediately followed by the class name (Welcome1). Keywords (sometimes called reserved words) are reserved for use by Java (we discuss the various keywords throughout the text) and are always spelled with all lowercase letters. The complete list of Java keywords is shown in Appendix C.

By convention, all class names in Java begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). A Java class name is an identifiera series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces. Some valid identifiers are Welcome1, $value, _value, m_inputField1 and button7. The name 7button is not a valid identifier because it begins with a digit, and the name input field is not a valid identifier because it contains a space. Normally, an identifier that does not begin with a capital letter is not the name of a Java class. Java is case sensitivethat is, uppercase and lowercase letters are distinct, so a1 and A1 are different (but both valid) identifiers.

Good Programming Practice 2.3

By convention, always begin a class name's identifier with a capital letter and start each subsequent word in the identifier with a capital letter. Java programmers know that such identifiers normally represent Java classes, so naming your classes in this manner makes your programs more readable.

Common Programming Error 2.2

Java is case sensitive. Not using the proper uppercase and lowercase letters for an identifier normally causes a compilation error.

In Chapters 27, every class we define begins with the public keyword. For now, we will simply require this keyword. When you save your public class declaration in a file, the file name must be the class name followed by the ".java" file-name extension. For our application, the file name is Welcome1.java. You will learn more about public and non-public classes in Chapter 8.

Common Programming Error 2.3

It is an error for a public class to have a file name that is not identical to the class name (plus the .java extension) in terms of both spelling and capitalization.

Common Programming Error 2.4

It is an error not to end a file name with the .java extension for a file containing a class declaration. If that extension is missing, the Java compiler will not be able to compile the class declaration.

A left brace (at line 5 in this program), {, begins the body of every class declaration. A corresponding right brace (at line 13), }, must end each class declaration. Note that lines 611 are indented. This indentation is one of the spacing conventions mentioned earlier. We define each spacing convention as a Good Programming Practice.

Good Programming Practice 2.4

Whenever you type an opening left brace, {, in your program, immediately type the closing right brace, }, then reposition the cursor between the braces and indent to begin typing the body. This practice helps prevent errors due to missing braces.

Good Programming Practice 2.5

Indent the entire body of each class declaration one "level" of indentation between the left brace, {, and the right brace, }, that delimit the body of the class. This format emphasizes the class declaration's structure and makes it easier to read.

Good Programming Practice 2.6

Set a convention for the indent size you prefer, and then uniformly apply that convention. The Tab key may be used to create indents, but tab stops vary among text editors. We recommend using three spaces to form a level of indent.

Common Programming Error 2.5

It is a syntax error if braces do not occur in matching pairs.

Line 6

 // main method begins execution of Java application

is an end-of-line comment indicating the purpose of lines 711 of the program. Line 7

 public static void main( String args[] )

is the starting point of every Java application. The parentheses after the identifier main indicate that it is a program building block called a method. Java class declarations normally contain one or more methods. For a Java application, exactly one of the methods must be called main and must be defined as shown on line 7; otherwise, the JVM will not execute the application. Methods are able to perform tasks and return information when they complete their tasks. Keyword void indicates that this method will perform a task but will not return any information when it completes its task. Later, we will see that many methods return information when they complete their task. You will learn more about methods in Chapters 3 and 6. For now, simply mimic main's first line in your Java applications. In Line 7, the String args[] in parentheses is a required part of the method main's declaration. We discuss this in Chapter 7, Arrays.

The left brace, {, on line 8 begins the body of the method declaration. A corresponding right brace, }, must end the method declaration's body (line 11 of the program). Note that line 9 in the body of the method is indented between the braces.

Good Programming Practice 2.7

Indent the entire body of each method declaration one "level" of indentation between the left brace, {, and the right brace, }, that define the body of the method. This format makes the structure of the method stand out and makes the method declaration easier to read.

Line 9

 System.out.println( "Welcome to Java Programming!" );

instructs the computer to perform an actionnamely, to print the string of characters contained between the double quotation marks. A string is sometimes called a character string, a message or a string literal. We refer to characters between double quotation marks simply as strings. White-space characters in strings are not ignored by the compiler.

System.out is known as the standard output object.System.out allows Java applications to display sets of characters in the command window from which the Java application executes. In Microsoft Windows 95/98/ME, the command window is the MS-DOS prompt. In Microsoft Windows NT/2000/XP, the command window is the Command Prompt. In UNIX/Linux/Mac OS X, the command window is called a terminal window or a shell. Many programmers refer to the command window simply as the command line.

Method System.out.println displays (or prints) a line of text in the command window. The string in the parentheses on line 9 is the argument to the method. Method System.out.println performs its task by displaying (also called outputting) its argument in the command window. When System.out.println completes its task, it positions the output cursor (the location where the next character will be displayed) to the beginning of the next line in the command window. (This move of the cursor is similar to when a user presses the Enter key while typing in a text editorthe cursor appears at the beginning of the next line in the file.)

The entire line 9, including System.out.println, the argument "Welcome to Java Programming!" in the parentheses and the semicolon (;), is called a statement. Each statement ends with a semicolon. When the statement on line 9 of our program executes, it displays the message Welcome to Java Programming! in the command window. As we will see in subsequent programs, a method is typically composed of one or more statements that perform the method's task.

Common Programming Error 2.6

Omitting the semicolon at the end of a statement is a syntax error.

Error-Prevention Tip 2.1

When learning how to program, sometimes it is helpful to "break" a working program so you can familiarize yourself with the compiler's syntax-error messages. These messages do not always state the exact problem in the code. When you encounter such syntax-error messages in the future, you will have an idea of what caused the error. Try removing a semicolon or brace from the program of Fig. 2.1, then recompile the program to see the error messages generated by the omission.

Error-Prevention Tip 2.2

When the compiler reports a syntax error, the error may not be on the line number indicated by the error message. First, check the line for which the error was reported. If that line does not contain syntax errors, check several preceding lines.

Some programmers find it difficult when reading or writing a program to match the left and right braces ({ and }) that delimit the body of a class declaration or a method declaration. For this reason, some programmers include an end-of-line comment after a closing right brace (}) that ends a method declaration and after a closing right brace that ends a class declaration. For example, line 11

 } // end method main

specifies the closing right brace (}) of method main, and line 13

 } // end class Welcome1

specifies the closing right brace (}) of class Welcome1. Each comment indicates the method or class that the right brace terminates.

Good Programming Practice 2.8

Following the closing right brace (}) of a method body or class declaration with an end-of-line comment indicating the method or class declaration to which the brace belongs improves program readability.

 

Compiling and Executing Your First Java Application

We are now ready to compile and execute our program. For this purpose, we assume you are using the Sun Microsystems' J2SE Development Kit. On the Downloads page at our Web site (www.deitel.com), we provide Deitel® Dive Into™ Series publications to help you begin using several popular Java development tools.

To prepare to compile the program, open a command window and change to the directory where the program is stored. Most operating systems use the command cd to change directories. For example,

 cd c:examplesch02fig02_01

changes to the fig02_01 directory on Windows. The command

 cd ~/examples/ch02/fig02_01

changes to the fig02_01 directory on UNIX/Linux/Max OS X.

To compile the program, type

 javac Welcome1.java

If the program contains no syntax errors, the preceding command creates a new file called Welcome1.class (known as the class file for Welcome1) containing the Java bytecodes that represent our application. When we use the java command to execute the application, these bytecodes will be executed by the JVM.

Error-Prevention Tip 2.3

When attempting to compile a program, if you receive a message such as "bad command or filename," "javac: command not found" or "'javac' is not recognized as an internal or external command, operable program or batch file," then your Java software installation was not completed properly. If you are using the J2SE Development Kit, this indicates that the system's PATH environment variable was not set properly. Please review the J2SE Development Kit installation instructions at java.sun.com/j2se/5.0/install.html carefully. On some systems, after correcting the PATH, you may need to reboot your computer or open a new command window for these settings to take effect.

Error-Prevention Tip 2.4

The Java compiler generates syntax-error messages when the syntax of a program is incorrect. Each error message contains the file name and line number where the error occurred. For example, Welcome1.java:6 indicates that an error occurred in the file Welcome1.java at line 6. The remainder of the error message provides information about the syntax error.

Error-Prevention Tip 2.5

The compiler error message "Public class ClassName must be defined in a file called ClassName.java" indicates that the file name does not exactly match the name of the public class in the file or that you typed the class name incorrectly when compiling the class.

Figure 2.2 shows the program of Fig. 2.1 executing in a Microsoft® Windows® XP Command Prompt window. To execute the program, type java Welcome1. This launches the JVM, which loads the ".class" file for class Welcome1. Note that the ".class" filename extension is omitted from the preceding command; otherwise, the JVM will not execute the program. The JVM calls method main. Next, the statement at line 9 of main displays "Welcome to Java Programming!" [Note: Many environments show command prompts with black backgrounds and white text. We adjusted these settings in our environment to make our screen captures more readable.]

Figure 2.2. Executing Welcome1 in a Microsoft Windows XP Command Prompt window.

Error-Prevention Tip 2.6

When attempting to run a Java program, if you receive a message such as "Exception in thread "main" java.lang.NoClassDefFoundError: Welcome1," your CLASSPATH environment variable has not been set properly. Please review the J2SE Development Kit installation instructions carefully. On some systems, you may need to reboot your computer or open a new command window after configuring the CLASSPATH.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net