Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

2.2 Your First Program in Java: Printing a Line of Text

A Java application is a computer program that executes when you use the java command to launch the Java Virtual Machine (JVM). Later in this section we'll discuss how to compile and run a Java application. First we consider a simple application that displays a line of text. Figure 2.16 shows the program followed by a box that displays its output. The program includes line numbers. We've added these for instructional purposes—they're not part of a Java program. This example illustrates several important Java features. We'll see that line 9 does the real work—displaying the phrase Welcome to Java Programming! on the screen.

Fig 2.1. Text-printing program.

 1  // Fig. 2.1: Welcome1.java
 2  // Text-printing program.
 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

Commenting Your Programs

We insert comments to document programs and improve their readability. The Java compiler ignores comments, so they do not cause the computer to perform any action when the program is run.

By convention, we begin every program with a comment indicating the figure number and file name. The comment in line 1

// Fig. 2.1: Welcome1.java

begins with //, indicating that it is an end-of-line comment—it terminates at the end of the line on which the // appears. An end-of-line comment 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

// Text-printing program.

is a comment that describes the purpose of the program.

Java also has traditional comments, which can be spread over several lines as in

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

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. The javadoc utility program (part of the Java SE 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 M, Creating Documentation with javadoc.

Using Blank Lines

Line 3 is a blank line. Blank lines, space characters and tabs make programs easier to read. Together, they're known as white space (or whitespace). The compiler ignores white space.

Declaring a Class

Line 4

public class Welcome1

begins a class declaration for class Welcome1. Every Java program consists of at least one class that you (the programmer) define. The class keyword introduces a class declaration and is immediately followed by the class name (Welcome1). Keywords (sometimes called reserved words) are reserved for use by Java and are always spelled with all lowercase letters. The complete list of keywords 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 an identifier—a 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 a class name. Java is case sensitive—uppercase and lowercase letters are distinct—so value and Value are different (but both valid) identifiers.

In Chapters 2–7, every class we define begins with the public keyword. For now, we simply require this keyword. For our application, the file name is Welcome1.java. You'll learn more about public and non-public classes in Chapter 8.

A left brace (as in line 5), { , begins the body of 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

// main method begins execution of Java application

is an end-of-line comment indicating the purpose of lines 7–10 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's a program building block called a method. Java class declarations normally contain one or more methods. For a Java application, one of the methods must be called main and must be defined as shown in line 7; otherwise, the Java Virtual Machine (JVM) will not execute the application. Methods perform tasks and can return information when they complete their tasks. Keyword void indicates that this method will not return any information. Later, we'll see how a method can return information. 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.

The left brace in line 8 begins the body of the method declaration. A corresponding right brace must end it (line 10). Line 9 in the method body is indented between the braces.

Performing Output with System.out.println

Line 9

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

instructs the computer to perform an action—namely, to print the string of characters contained between the double quotation marks (but not the quotation marks themselves). A string is sometimes called a character string or a string literal. White-space characters in strings are not ignored 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.

The System.out object is known as the standard output object. It allows a Java applications to display information in the command window from 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 a terminal window or a shell. Many programmers call it simply the command line.

Method System.out.println displays (or prints) a line of text in the command window. The string in the parentheses in line 9 is the argument to the method. When System.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. This is similar to what happens when you press the Enter key while typing in a text editor—the cursor appears at the beginning of the next line in the document.

The entire line 9, including System.out.println, the argument "Welcome to Java Programming!" in the parentheses and the semicolon ( ; ), is called a statement. A method typically contains one or more statements that perform its task. Most statements end with a semicolon. When the statement in line 9 executes, it displays Welcome to Java Programming! 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

} // end method main

indicates the closing brace of method main, and line 11

} // end class Welcome1

indicates the closing brace of class Welcome1. Each comment indicates the method or class that the right brace terminates.

Compiling and Executing Your First Java Application

We're now ready to compile and execute our program. We assume you're using the Java Development Kit's command-line tools, not an IDE. Our Java Resource Centers at www.deitel.com/ResourceCenters.html provide 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/jhtp9/ 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 command cd to change directories. On Windows, for example,

cd c:\examples\ch02\fig02_01

changes to the fig02_01 directory. On UNIX/Linux/Max OS X, the command

cd ~/examples/ch02/fig02_01

changes to the fig02_01 directory.

To compile the program, type

javac Welcome1.java

If the program contains no syntax errors, this command creates a new file called Welcome1.class (known as the class file for Welcome1) containing the platform-independent Java bytecodes that represent our application. When we use the java command 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.

Figure 2.2 shows the program of Fig. 2.1 executing in a Microsoft® Windows® 7 Command Prompt window. To execute the program, type java Welcome1. This command launches the JVM, which loads the .class file for class Welcome1. The command omits the .class file-name extension; 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

Fig. 2.2 Executing Welcome1 from the Command Prompt.

  • + Share This
  • 🔖 Save To Your Account