A Javaapplicationis a computer program that executes when you use thejavacommand to launch the Java Virtual Machine (JVM). Later in this section we’ll discuss how to com- pile and run a Java application. First we consider a simple application that displays a line of text. Figure 2.1 shows the program followed by a box that displays its output. The program includes line numbers. We’ve added these for instructional purposes—they’renotpart of a Java program. This example illustrates several important Java features. We’ll see that line 9 does the real work—displaying the phraseWelcome to Java Programming!on the screen.
Commenting Your Programs
By convention, we begin every program with a comment indicating the figure number and file name. The comment in line 1 begins with//, indicating that it is anend-of-line com-
2.1 Introduction
2.2 Your First Program in Java: Printing a Line of Text
2.3 Modifying Your First Java Program 2.4 Displaying Text withprintf 2.5 Another Application: Adding Integers
2.6 Arithmetic
2.7 Decision Making: Equality and Relational Operators
2.8 Wrap-Up
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 } // end method main 11 } // end class Welcome1
Welcome to Java Programming!
Fig. 2.1 | Text-printing program.
24 Chapter 2 Introduction to Java Applications
ment—it terminates at the end of the line on which the//appears. An end-of-line com- ment need not begin a line; it also can begin in the middle of a line and continue until the end (as in lines 10 and 11). Line 2 is a comment that describes the purpose of the program.
Java also hastraditional comments, which can be spread over several lines as in
These begin and end with delimiters,/*and*/. The compiler ignores all text between the delimiters. Java incorporated traditional comments and end-of-line comments from the C and C++ programming languages, respectively. In this book, we use only//comments.
Java provides comments of a third type, Javadoc comments. These are delimited by
/** and */. The compiler ignores all text between the delimiters. Javadoc comments enable you to embed program documentation directly in your programs. Such comments are the preferred Java documenting format in industry. Thejavadocutility program(part of the Java SE Development Kit) reads Javadoc comments and uses them to prepare your program’s documentation in HTML format.
Using Blank Lines
Line 3 is a blank line. Blank lines, space characters and tabs make programs easier to read.
Together, they’re known aswhite space(or whitespace). The compiler ignores white space.
Declaring a Class
Line 4 begins aclass declarationfor classWelcome1. Every Java program consists of at least one class that you (the programmer) define. Theclasskeywordintroduces a class decla- ration and is immediately followed by theclass name(Welcome1).Keywordsare reserved for use by Java and are always spelled with all lowercase letters. The complete list of key- words is shown in Appendix C.
Class Names and Identifiers
By convention, class names begin with a capital letter and capitalize the first letter of each word they include (e.g.,SampleClassName). A class name is anidentifier—a series of char- acters 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_inputField1andbutton7. The name7buttonis not a valid identifier because it begins with a digit, and the nameinput fieldis not a valid identifier because it con- tains a space. Normally, an identifier that does not begin with a capital letter is not a class name. Java iscase sensitive—uppercase and lowercase letters are distinct—sovalueand
Valueare different (but both valid) identifiers.
In Chapters 4–7, every class we define begins with thepublickeyword. For now, we simply require this keyword. For our application, the file name isWelcome1.java. You’ll learn more aboutpublicand non-publicclasses in Chapter 8.
/* This is a traditional comment. It can be split over multiple lines */
Common Programming Error 2.1
Apublicclass must be placed in a file that has the same name as the class (in terms of both spelling and capitalization) plus the.javaextension; otherwise, a compilation error occurs. For example,publicclassWelcomemust be placed in a file namedWelcome.java.
2.2 Your First Program in Java: Printing a Line of Text 25
Aleft brace(as in line 5),{, begins thebodyof every class declaration. A corresponding right brace(at line 11),}, must end each class declaration. Lines 6–10 are indented.
Declaring a Method
Line 6 is an end-of-line comment indicating the purpose of lines 7–10. Line 7 is the starting point of every Java application. Theparenthesesafter the identifiermainindicate that it’s a method. Java class declarations normally contain one or more methods. For a Java applica- tion, one of the methodsmustbe calledmainand must be defined as shown in line 7; oth- erwise, the Java Virtual Machine (JVM) will not execute the application. Methods perform tasks and can return information when they complete their tasks. Keywordvoidindicates that this method willnotreturn any information. In line 7, theString[] argsin parenthe- ses is a required part of the methodmain’s declaration—we discuss this in Chapter 7.
The left brace in line 8 begins thebody of the method declaration. A corresponding right brace ends it (line 10). Line 9 in the method body is indented between the braces.
Performing Output withSystem.out.println
Line 9 instructs the computer to perform an action—namely, to print thestringof char- acters contained between the double quotation marks (but not the quotation marks them- selves). White-space characters in strings arenotignored by the compiler. Strings cannot span multiple lines of code, but as you’ll see later, this does not restrict you from using long strings in your code.
TheSystem.outobject is known as thestandard output object. It allows a Java appli- cations to display information in thecommand windowfrom which it executes. In recent versions of Microsoft Windows, the command window is the Command Prompt. In UNIX/Linux/Mac OS X, the command window is called aterminal window or ashell.
Many programmers call it simply thecommand line.
MethodSystem.out.printlndisplays a line of text in the command window. The string in the parentheses in line 9 is the method’sargument. WhenSystem.out.println
completes its task, it positions the output cursor (the location where the next character will be displayed) at the beginning of the next line in the command window.
The entire line 9, includingSystem.out.println, the argument"Welcome to Java Programming!"in the parentheses and thesemicolon(;), is called astatement. A method
Good Programming Practice 2.1
Indent the entire body of each class declaration one “level” between the left brace and the right brace that delimit the body of the class. We recommend using three spaces to form a level of indent. This format emphasizes the class declaration’s structure and makes it easier to read.
Good Programming Practice 2.2
Many IDEs insert indentation for you in all the right places. TheTabkey may also be used to indent code, but tab stops vary among text editors. Most IDEs allow you to configure tabs such that a specified number of spaces is inserted each time you press theTabkey.
Good Programming Practice 2.3
Indent the entire body of each method declaration one “level” between the braces that de- fine the body of the method.
26 Chapter 2 Introduction to Java Applications
typically contains one or more statements that perform its task. Most statements end with a semicolon. When the statement in line 9 executes, it displaysWelcome to Java Program- ming!in the command window.
Using End-of-Line Comments on Right Braces for Readability
We include an end-of-line comment after a closing brace that ends a method declaration and after a closing brace that ends a class declaration. For example, line 10 indicates the closing brace of methodmain, and line 11 indicates the closing brace of classWelcome1. Each comment indicates the method or class that the right brace terminates.
Compiling and Executing Your First Java Application
We assume you’re using the Java Development Kit’s command-line tools, not an IDE.
Our Java Resource Centers atwww.deitel.com/ResourceCenters.htmlprovide links to tutorials that help you get started with several popular Java development tools, including NetBeans™, Eclipse™ and others. We’ve also posted NetBeans and Eclipse videos at
www.deitel.com/books/javafp2/to help you get started using these popular IDEs.
To prepare to compile the program, open a command window and change to the directory where the program is stored. Many operating systems use the commandcdto change directories. On Windows, for example,
changes to thefig02_01directory. On UNIX/Linux/Max OS X, the command
changes to thefig02_01directory.
To compile the program, type
If the program contains no syntax errors, this command creates a new file called
Welcome1.class(known as theclass fileforWelcome1) containing the platform-indepen- dent Java bytecodes that represent our application. When we use thejavacommand to execute the application on a given platform, the JVM will translate these bytecodes into instructions that are understood by the underlying operating system and hardware.
cd c:\examples\ch02\fig02_01
cd ~/examples/ch02/fig02_01
javac Welcome1.java
Error-Prevention Tip 2.1
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 inter- nal or external command, operable program or batch file,” then your Java software installation was not completed properly. If you’re using the JDK, this indicates that the system’sPATHenvironment variable was not set properly. Please carefully review the in- stallation instructions in the Before You Begin section of this book. On some systems, after correcting thePATH, you may need to reboot your computer or open a new command win- dow for these settings to take effect.
Error-Prevention Tip 2.2
Each syntax-error message contains the file name and line number where the error oc- curred. For example,Welcome1.java:6indicates that an error occurred at line 6 in
Welcome1.java. The rest of the message provides information about the syntax error.