Chapter 1
IN THIS CHAPTER
Introducing the famous Hello, World! program
Identifying basic elements of Java programs such as keywords, statements, and blocks
Finding different ways to add comments to your programs
Getting basic information about object-oriented programming
Identifying ways to import classes
In this chapter, you find the basics of writing simple Java programs. The programs you see in this chapter are very simple: they just display simple information on a console (in Windows, that’s a command-prompt window). You need to cover a few more chapters before you start writing programs that do anything worthwhile. But the simple programs you see in this chapter are sufficient to illustrate the basic structure of Java programs.
Be warned that in this chapter, I introduce you to several Java programming features that are explained in greater detail in later chapters. You see, for example, some variable declarations, a method, and even an if
statement and a for
loop. The goal of this chapter isn’t to march you into instant proficiency with these programming elements, but just to introduce you to them.
Many programming books begin with a simple example program that displays the text "Hello, World!"
on the console. In Book 1, Chapter 1, I show you a Java program that does that to compare it with a similar program written in C. Now take a closer look at each element of this program, shown in Listing 1-1.
LISTING 1-1 The HelloApp Program
public class HelloApp →1
{ →2
public static void main(String[] args) →3
{ →4
System.out.println("Hello, World!"); →5
} →6
} →7
Later in this chapter, you discover in detail all the elements that make up this program. But first, I want to walk you through it word by word.
Lines 1 and 2 mark the declaration of a public class named HelloApp
:
→1 public
: A keyword of the Java language that indicates that the element that follows should be made available to other Java elements. In this case, what follows is a class named HelloApp
. As a result, this keyword indicates that the HelloApp
class is a public class, which means other classes can use it. (In Book 3, Chapter 2, I cover the most common alternative to public: private
. There are also other alternatives, but they’re covered in later chapters.)
class
: Another Java keyword that indicates that the element being defined here is a class. All Java programs are made up of one or more classes. A class definition contains code that defines the behavior of the objects created and used by the program. Although most real-world programs consist of more than one class, the simple programs you see in this minibook have just one class.
HelloApp
: An identifier that provides the name for the class being defined here. Whereas keywords, such as public
and class
, are words that are defined by the Java programming language, identifiers are words that you create to provide names for various elements you use in your program. In this case, the identifier HelloApp
provides a name for the public class being defined here. (Although identifier is the technically correct term, sometimes identifiers are called symbols or names.)
→2 {
: The opening brace on line 2 marks the beginning of the body of the class. The end of the body is marked by the closing brace on line 7. Everything that appears within these braces belongs to the class. As you work with Java, you’ll find that it uses these braces a lot. Pretty soon the third and fourth fingers on your right hand will know exactly where they are on the keyboard.
Lines 3 through 6 define a method of the HelloApp
class named main
:
→3 public
: The public
keyword is used again, this time to indicate that a method being declared here should have public access. That means classes other than the HelloApp
class can use it. All Java programs must have a class that declares a public method named main
. The main
method contains the statements that are executed when you run the program.
static
: You find all about the static
keyword in Book 3, Chapter 3. For now, just take my word that the Java language requires that you specify static
when you declare the main
method.
void
: In Java, a method is a unit of code that can calculate and return a value. For example, you could create a method that calculates a sales total. Then the sales total would be the return value of the method. If a method doesn’t need to return a value, you must use the void
keyword to indicate that no value is returned. Because Java requires that the main
method not return a value, you must specify void
when you declare the main
method.
main
: Finally, here’s the identifier that provides the name for this method. As I’ve already mentioned, Java requires that this method be named main
. Besides the main
method, you can create additional methods with whatever names you want to use. You discover how to create additional methods in Book 2, Chapter 7. Until then, the programs consist of just one method named main
.
(String[] args)
: Oh, boy. This Java element is too advanced to thoroughly explain just yet. It’s called a parameter list, and it’s used to pass data to a method. Java requires that the main
method must receive a single parameter that’s an array of String
objects. By convention, this parameter is named args
. If you don’t know what a parameter, a String
, or an array is, don’t worry about it. You can find out what a String
is in the next chapter, and parameters are in Book 2, Chapter 7; arrays are in Book 4. In the meantime, realize that you have to code (String[] args
) on the declaration for the main
methods in all your programs.
→4 Another{
: Another set of braces begins at line 4 and ends at line 6. These braces mark the body of the main
method. Notice that the closing brace in line 6 is paired with the opening brace in line 4, whereas the closing brace in line 7 is paired with the one in line 2. This type of pairing is commonplace in Java. In short, whenever you come to a closing brace, it’s paired with the most recent opening brace that hasn’t already been closed — that is, that hasn’t already been paired with a closing brace.
→5 System.out.println("Hello, World!");
: This is the only statement in the entire program. It calls a method named println
that belongs to the System.out
object. The println
method displays a line of text on the console. The text to be displayed is passed to the println
method as a parameter in parentheses following the word println
. In this case, the text is the string literal Hello, World!
enclosed in a set of quotation marks. As a result, this statement displays the text Hello, World!
on the console.
Note that in Java, most (but not all) statements must end with a semicolon. Because this statement is the only one in the program, this line is the only one that requires a semicolon.
→6 }
: Line 6 contains the closing brace that marks the end of the main
method body that was begun by the brace on line 4.
→7 Another }
: Line 7 contains the closing brace that marks the end of the HelloApp
class body that was begun by the brace on line 2. Because this program consists of just one class, this line also marks the end of the program.
To run this program, you must first use a text editor such as Notepad or TextPad to enter it — exactly as it appears in Listing 1-1 — in a text file named HelloApp.java
. Then you can compile it by running the following command at a command prompt:
javac HelloApp.java
This command creates a class file named HelloApp.class
that contains the Java bytecodes compiled for the HelloApp class
.
You can run the program by entering this command:
java HelloApp
Now that you’ve seen what a Java program actually looks like, you’re in a better position to understand exactly what this command does. First, it loads the Java Virtual Machine (JVM) into memory. Then it locates the HelloApp
class, which must be contained in a file named HelloApp.class
. Finally, it runs the main
method of the HelloApp
class. The main
method, in turn, displays the message "Hello, World!"
on the console.
The rest of this chapter describes some of the basic elements of the Java programming language in greater detail.
A keyword is a word that has a special meaning defined by the Java programming language. The program shown earlier in Listing 1-1 uses four keywords: public
, class
, static
, and void
. In all, Java has 53 keywords. They’re listed in alphabetical order in Table 1-1.
TABLE 1-1 Java’s Keywords
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Stranger still, two keywords — const
and goto
— are reserved by Java but don’t do anything. Both are carryovers from the C++ programming language. The const
keyword defines a constant, which is handled in Java by the final
keyword. As for goto
, it’s a C++ statement that is considered anathema to object-oriented programming purists, so it isn’t used in Java. Java reserves it as a keyword solely for the purpose of scolding you if you attempt to use it.
Considering the Java community’s disdain for Visual Basic, it’s surprising that the error messages generated when you capitalize keywords aren’t more insulting. Accidentally capitalizing a keyword in Visual Basic style can really throw the Java compiler for a loop. Consider this program, which contains the single error of capitalizing the word For
:
public class CaseApp
{
public static void main(String[] args)
{
For (int i = 0; i<5; i++)
System.out.println("Hi");
}
}
When you try to compile this program, the compiler generates a total of four error messages for this one mistake:
C:Java AIOCaseApp.java:5: '.class' expected
For (int i = 0; i<5; i++)
^
C:Java AIOCaseApp.java:5: illegal start of type
For (int i = 0; i<5; i++)
^
C:Java AIOCaseApp.java:5: not a statement
For (int i = 0; i<5; i++)
^
C:Java AIOCaseApp.java:5: ';' expected
For (int i = 0; i<5; i++)
^
4 errors For (int i = 0; i<5; i++)
Even though this single mistake generates four error messages, not one of the messages actually points to the problem. The little arrow beneath the source line indicates what part of the line is in error, and none of these error messages has the arrow pointing anywhere near the word For
! The compiler isn’t smart enough to realize that you meant for
instead of For
. So it treats For
as a legitimate identifier and then complains about everything else on the line that follows it. It would be much more helpful if the compiler generated an error message like this:
C:Java AIOCaseApp.java:5: 'For' is not a keyword
For (int i = 0; i<5; i++)
Better yet, for those of us old enough to remember Get Smart on TV:
C:Java AIOCaseApp.java:5: Thees ees Java! Vee do not capitalize keyverds here!
For (int i = 0; i<5; i++)
Like most programming languages, Java uses statements to build programs. Unlike most programming languages, Java doesn’t use statements as its fundamental unit of code. Instead, it gives that honor to the class. However, every class must have a body, and the body of a class is made up of one or more statements. In other words, you can’t have a meaningful Java program without at least one statement. The following sections describe the ins and outs of working with Java statements.
Java has many types of statements. Some statements simply create variables that you can use to store data. These types of statements are often called declaration statements and tend to look like this:
int i;
String s = "This is a string";
Customer c = new Customer();
Another common type of statement is an expression statement, which performs calculations. Here are some examples of expression statements:
i = a + b;
salesTax = invoiceTotal * taxRate;
System.out.println("Hello, World!");
Notice that the last statement in this group is the same as line 5 in Listing 1-1. Thus the single statement in the HelloApp
program is an expression statement.
There are many kinds of statements besides these two. if-then
statements, for example, execute other statements only if a particular condition has been met, and statements such as for
, while
, and do
execute whole groups of statements one or more times.
if (total > 100)
discountPercent = 10;
Here, the variable named discountPercent
is given a value of 10
if the value of the total variable is greater than 100
. The expression statement ends with a semicolon, but the if
statement itself doesn’t. (The Java compiler lets you know if you use a semicolon when you shouldn’t.)
In Java, the term white space refers to one or more consecutive space characters, tab characters, or line breaks. All white space is considered the same.
If you’ve programmed in Visual Basic, white space is different from what you’re used to. In Visual Basic, line breaks mark the end of statements unless special continuation characters are used. In Java, you don’t have to do anything special to continue a statement onto a second line. Thus the statement
x = (y + 5) / z;
is identical to this statement:
x =
(y + 5) / z;
In fact, you could write the preceding statement like this if you wanted:
x
=
(
y
+
5
)
/
z
;
I wouldn’t advise it, but the statement does compile and execute properly.
Be advised, however, that you can’t put white space in the middle of a keyword or identifier. The following example won’t work:
p u b l i c static v o i d main(String[] args)
Here the extra spaces between the letters in the words public and void will confuse the compiler.
The compiler ignores the extra white space, so it doesn’t affect the bytecode that’s created for your program. As a result, using extra white space in your program doesn’t affect your program’s performance in any way, but it does make the program’s source code easier to read.
A block is a group of one or more statements that’s enclosed in braces. A block begins with an opening brace ( {
) and ends with a closing brace ( }
). Between the opening and closing braces, you can code one or more statements. Here’s a block that consists of three statements:
{
int i, j;
i = 100;
j = 200;
}
if ( expression ) statement
Here statement
can be a single statement or a block. If you find this idea confusing, don’t worry; it will make more sense when you turn to Book 2, Chapter 4.
if ( i > 0)
{
String s = "The value of i is " + i;
System.out.print(s);
}
The other style is to place the opening brace for the block on the same line as the statement the block is associated with, like this:
if ( i > 0) {
String s = "The value of i is " + i;
System.out.print(s);
}
Which style you use is a matter of personal preference. I prefer the first style, and that’s the style I use throughout this book. But either style works — and many programmers prefer the second style because it’s more concise.
An identifier is a word that you make up to refer to a Java programming element by name. Although you can assign identifiers to many types of Java elements, they’re most commonly used for the following elements:
HelloApp
class in Listing 1-1main
method in Listing 1-1SalesTax
and salesTax
are distinct identifiers.$
). Thus, identifier names such as Port1
, SalesTax$
, and Total_Sales
.a15
is a valid identifier, but 13Unlucky
isn’t (because it begins with a numeral).for
or a class named public
.A comment is a bit of text that provides explanations of your code. The compiler ignores comments, so you can place any text you want in a comment. Using plenty of comments in your program is a good way to explain what your program does and how it works.
Java has three basic types of comments: end-of-line comments, traditional comments, and JavaDoc comments. More about that is coming right up.
An end-of-line comment begins with the sequence //
(a pair of consecutive slashes) and ends at the end of the line. You can place an end-of-line comment at the end of any line. Everything you type after the //
is ignored by the compiler. For example:
total = total * discountPercent; // calculate the discounted total
If you want, you can also place end-of-line comments on separate lines, like this:
// calculate the discounted total
total = total * discountPercent;
You can place end-of-line comments in the middle of statements that span two or more lines. For example:
total = (total * discountPercent) // apply the discount first
+ salesTax; // then add the sales tax
A traditional comment begins with the sequence /*
, ends with the sequence */
, and can span multiple lines. Here’s an example:
/* HelloApp sample program.
This program demonstrates the basic structure
that all Java programs must follow. */
A traditional comment can begin and end anywhere on a line. If you want, you can even sandwich a comment between other Java programming elements, like this:
x = (y + /* a strange place for a comment */ 5) / z;
Usually, traditional comments appear on separate lines. One common use for traditional comments is to place a block of comment lines at the beginning of a class to indicate information about the class — such as what the class does, who wrote it, and so on. That type of comment, however, is usually better coded as a JavaDoc comment, as described in the next section.
/*
int x, y, z;
y = 10;
z = 5;
x = (y + /* a strange place for a comment */ 5) / z;
*/
Here, I tried to comment out a range of lines that already included a traditional comment. Unfortunately, the */
sequence near the end of the fifth line is interpreted as the end of the traditional comment that begins in the first line, so when the compiler encounters the */
sequence in line 6, it generates an error message.
JavaDoc comments are actually special types of traditional comments that you can use to create web-based documentation for your programs — automatically. Because you’ll have a better appreciation of JavaDoc comments when you know more about object-oriented programming, I devote a section in Book 3, Chapter 8, to creating and using JavaDoc comments.
Having presented some of the most basic elements of the Java programming language, most Java books would next turn to the important topics of variables and data types. Because Java is an inherently object-oriented programming language, however, and because classes are the heart of object-oriented programming, I look next at classes to explore the important role they play in creating objects. I get to variables and data types first thing in the next chapter.
As I’ve already mentioned, a class is code that defines the behavior of a Java programming element called an object. An object is an entity that has both state and behavior. The state of an object consists of any data that the object might be keeping track of, and the behavior consists of actions that the object can perform. The behaviors are represented in the class by one or more methods that can be called on to perform actions.
The difference between a class and an object is similar to the difference between a blueprint and a house. A blueprint is a plan for a house. A house is an implementation of a blueprint. One set of blueprints can be used to build many houses. Likewise, a class is a plan for an object, and an object is — in Java terms — an instance of a class. You can use a single class to create more than one object.
When an object is created, Java sets aside an area of computer memory that’s sufficient to hold all the data that’s stored by the object. As a result, each instance of a class has its own data, independent of the data used by other instances of the same class.
You don’t necessarily have to create an instance of a class to use the methods of the class. If you declare a method with the static
keyword, you can call the method without first creating an instance of the class, because static
methods are called from classes, not from objects.
The main
method of a Java application must be declared with the static
keyword because when you start a Java program by using the java
command from a command prompt, Java doesn’t create an instance of the application class. Instead, it simply calls the program’s static main
method.
The difference between static and nonstatic methods will become more apparent when you look at object-oriented programming in more depth in Book 3. But for now, consider this analogy. The blueprints for a house include the details about systems that actually perform work in a finished house, such as electrical and plumbing systems. To use those systems, you have to actually build a house. In other words, you can’t turn on the hot water by using the blueprint alone; you have to have an actual house with an actual device to heat the water.
The blueprints do include detailed measurements of the dimensions of the house, however. As a result, you can use the blueprints to determine the square footage of the living room.
Now imagine that the blueprints actually have a built-in calculator that displays the size of the living room if you push the Living Room button. That button would be like a static
method in a class: You don’t actually have to build a house to use the button; you can activate it from the blueprints alone.
Many Java programs — in fact, many of the programs in the rest of Book 2 — are entirely made up of static
methods. Most realistic programs, however, require that you create one or more objects that the program uses as it executes. As a result, knowing how to create simple classes and how to create objects from those classes are basic skills in Java programming.
In Java, you can create an object from a class in several ways. The most straightforward way is to create a variable that provides a name you can use to refer to the object, use the new
keyword to create an instance of the class, and then assign the resulting object to the variable. The general form of a statement that does that bit of magic looks like this:
ClassName variableName = new ClassName();
To create an object instance of a class named Class1
and assign it to a variable named myClass1Object
, you would write a statement like this:
Class1 myClass1Object = new Class1();
Why do you have to list the class name twice? The first time, you’re providing a type for the variable. In other words, you’re saying that the variable you’re creating here can be used to hold objects created from the Class1
class. The second time you list the class name, you’re creating an object from the class. The new
keyword tells Java to create an object, and the class name provides the name of the class to use to create the object.
The equal sign (=
) is an assignment operator. It simply says to take the object created by the new
keyword and assign it to the variable. Thus, this statement actually does three things:
myClass1Object
that can be used to hold objects created from the Class1
class. At this point, no object has been created — just a variable that can be used to store objects.Class1
class.myClass1Object
variable. That way, you can use the myClassObject
variable to refer to the object that was created.To give you an early look at what object-oriented programming really looks like, Listing 1-2 and Listing 1-3 show another version of the HelloApp
application — this time using two classes, one of which is actually made into an object when the program is run. The first class, named HelloApp2
, is shown in Listing 1-2. This class is similar to the HelloApp
class shown in Listing 1-1 but uses an object created from the second class, named Greeter
, to actually display the "Hello, World!"
message on the console. The Greeter
class is shown in Listing 1-3. It defines a method named sayHello
that displays the message.
The HelloApp2
class is shown in Listing 1-2.
LISTING 1-2 The HelloApp2 Class
// This application displays a hello message on →1
// the console by creating an instance of the
// Greeter class and then calling the Greeter
// object's sayHello method.
public class HelloApp2 →6
{
public static void main(String[] args) →8
{
Greeter myGreeterObject = new Greeter(); →10
myGreeterObject.sayHello(); →11
}
}
The following paragraphs describe the key points:
HelloApp2
class begins on line 6 with the public
class declaration. Because the public
keyword is used, a file named HelloApp2.java
must contain this class.main
method is declared, using the same form as the main
method in the first version of this program (Listing 1-1). Get used to this form, because all Java applications must include a main
method that’s declared in this way.myGreeterObject
that can hold objects created from the Greeter
class. Then it creates a new object using the Greeter
class and assigns this object to the myGreeterObject
variable.main
method calls the myGreeterObject
object’s sayHello
method. As you’ll see in a moment, this method simply displays the message "Hello, World!"
on the console.The Greeter
class is shown in Listing 1-3.
LISTING 1-3 The Greeter Class
// This class creates a Greeter object →1
// that displays a hello message on
// the console.
public class Greeter →5
{
public void sayHello() →7
{
System.out.println("Hello, World!"); →9
}
}
The following paragraphs describe the key points:
HelloApp2
class can access the Greeter
class.sayHello
method is declared using the public
keyword so that it’s available to other classes that use the Greeter
class. The void
keyword indicates that this method doesn’t provide any data back to the class that calls it, and sayHello
simply provides the name of the method."Hello, World!"
message on the console.You may notice that the only line that actually does any real work in the HelloApp2
program is line 9 in the Greeter
class (Listing 1-3), and this line happens to be identical to line 5 in the original HelloApp
class (Listing 1-1). Other than the fact that the second version requires roughly twice as much code as the first version, what really is the difference between these two applications?
Simply put, the first version is procedural, and the second is object-oriented. In the first version of the program, the main
method of the application class does all the work of the application by itself: It just says hello. The second version defines a class that knows how to say hello to the world and then creates an object from that class and asks that object to say hello. The application itself doesn’t know (or even care) exactly how the Greeter
object says hello. It doesn’t know exactly what the greeting will be, what language the greeting will be in, or even how the greeting will be displayed.
To illustrate this point, consider what would happen if you used the Greeter
class shown in Listing 1-4 rather than the one shown in Listing 1-3. This version of the Greeter
class uses a Java library class called JOptionPane
to display a message in a dialog box rather than in a console window. (I won’t bother explaining in a list how this code works, but you can find out more about it in the next chapter.) If you were to run the HelloApp2
application using this version of the Greeter
class, you’d get the dialog box shown in Figure 1-1.
LISTING 1-4 Another Version of the Greeter Class
// This class creates a Greeter object
// that displays a hello message
// in a dialog box.
import javax.swing.JOptionPane; →5
public class Greeter
{
public void sayHello()
{
JOptionPane.showMessageDialog(null, →11
"Hello, World!", "Greeter",
JOptionPane.INFORMATION_MESSAGE);
}
}
You may have noticed that the Greeter
class in Listing 1-4 includes this statement:
import javax.swing.JOptionPane;
The purpose of the import
statement is to let the compiler know that the program is using a class that’s defined by the Java API called JOptionPane
.
Because the Java API contains literally thousands of classes, some form of organization is needed to make the classes easier to access. Java does this by grouping classes into manageable groups called packages. In the previous example, the package that contains the JOptionPane
class is named javax.swing
.
Strictly speaking, import
statements are never required. But if you don’t use import
statements to import the API classes your program uses, you must fully qualify the names of the classes when you use them by listing the package name in front of the class name. So if the class in Listing 1-4 didn’t include the import
statement in line 5, you’d have to code line 11 like this:
javax.swing.JOptionPane.showMessageDialog(null,
"Hello, World!", "Greeter",
javax.swing.JOptionPane.INFORMATION_MESSAGE);
In other words, you’d have to specify javax.swing.JOptionPane
instead of just JOptionPane
whenever you referred to this class.
import
statements must appear at the beginning of the class file, before any class declarations.import
statements as are necessary to import all the classes used by your program.import javax.swing.*;
java.lang
package, you don’t have to import that package. Instead, those classes are automatically available to all programs. The System
class is defined in the java.lang
package. As a result, you don’t have to provide an import
statement to use this class.The latest version of Java, called JDK 9, introduces a new feature for managing packages called the Java Platform Module System. I cover this new feature in Book 3, Chapter 8.